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

后端 未结 3 1984
粉色の甜心
粉色の甜心 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:57

    You can make a decorator that is a global exception handler:

    import traceback
    from flask import current_app
    
    def set_global_exception_handler(app):
        @app.errorhandler(Exception)
        def unhandled_exception(e):
            response = dict()
            error_message = traceback.format_exc()
            app.logger.error("Caught Exception: {}".format(error_message)) #or whatever logger you use
            response["errorMessage"] = error_message
            return response, 500
    

    And wherever you create your app instance, you need to do this:

    from xxx.xxx.decorators import set_global_exception_handler
    app = Flask(__name__)
    set_global_exception_handler(app)
    

    This will handle all exceptions generated in your application along with whatever else you need to do to handle them. Hope this helps.

提交回复
热议问题