Global error handler for any exception

前端 未结 6 1628
旧时难觅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:23

    Far from elegant, but the following works for tying all subclasses of HTTPException to a single error handler:

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

提交回复
热议问题