Global error handler for any exception

前端 未结 6 1638
旧时难觅i
旧时难觅i 2020-12-04 18:07

Is there a way to add a global catch-all error handler in which I can change the response to a generic JSON response?

I can\'t use the got_request_exception

6条回答
  •  甜味超标
    2020-12-04 18:35

    A cleaner way to implement this in Flask >=0.12 would be to explicitly register the handler for every Werkzeug exception:

    from flask import jsonify
    from werkzeug.exceptions import HTTPException, default_exceptions
    
    app = Flask('test')
    
    def handle_error(error):
        code = 500
        if isinstance(error, HTTPException):
            code = error.code
        return jsonify(error='error', code=code)
    
    for exc in default_exceptions:
        app.register_error_handler(exc, handle_error)
    

提交回复
热议问题