how to not have the flask server break when an error occurs?

后端 未结 3 1985
粉色の甜心
粉色の甜心 2021-01-26 00:23

I have made an API app using flask, that takes a number(decimal) as input and returns some string. This app breaks if I send a string and works fine after re-starting it. I don\

3条回答
  •  我在风中等你
    2021-01-26 00:43

    When looking into the documents we can find this behaviour:

    handle_exception(e)

    Handle an exception that did not have an error handler associated with it, or that was raised from an error handler. This always causes a 500 InternalServerError.

    Always sends the got_request_exception signal.

    If propagate_exceptions is True, such as in debug mode, the error will be re-raised so that the debugger can display it. Otherwise, the original exception is logged, and an InternalServerError is returned.

    If an error handler is registered for InternalServerError or 500, it will be used. For consistency, the handler will always receive the InternalServerError. The original unhandled exception is available as e.original_exception.

    A way to catch this errors and do something with it could be this:

    @app.errorhandler(Exception)
    def handle_exception(e):
        # pass through HTTP errors
        if isinstance(e, HTTPException):
            return e
    
        # now you're handling non-HTTP exceptions only
        return render_template("500_generic.html", e=e), 500
    

    Source and extra documentation if needed you can find here:

    Flask pallets projects

提交回复
热议问题