Catching a 500 server error in Flask

后端 未结 6 1257
-上瘾入骨i
-上瘾入骨i 2021-02-01 12:41

I love Flask\'s error catching. It\'s beautifully simple:

@app.errorhandler(404)
def pageNotFound(error):
    return \"page not found\"

works

6条回答
  •  [愿得一人]
    2021-02-01 13:15

    The issue is that within the code, not all Exceptions are HTTPException, but Flask catches these by default and returns a generic 500 error response (which may or may not include the original error message as described by @Mark Hildreth). Thus, using @app.errorhandler(500) will not catch those errors, since this happens before Flask returns the generic 500 error.

    You would need to have a generic errorhandler(Exception) which works similar to except Exception: in python, which captures everything. A good solution is provided in Flask pallets projects:

    from werkzeug.exceptions import HTTPException
    
    @app.errorhandler(Exception)
    def handle_exception(e):
        # pass through HTTP errors. You wouldn't want to handle these generically.
        if isinstance(e, HTTPException):
            return e
    
        # now you're handling non-HTTP exceptions only
        return render_template("500_generic.html", e=e), 500
    

    You can also return JSON if you'd like and also include the original error message if you're in debug mode. E.g.

    from flask import jsonify
    from werkzeug.exceptions import HTTPException
    
    debug = True  # global variable setting the debug config
    
    @app.errorhandler(Exception)
    def handle_exception(e):
        if isinstance(e, HTTPException):
            return e
    
        res = {'code': 500,
               'errorType': 'Internal Server Error',
               'errorMessage': "Something went really wrong!"}
        if debug:
            res['errorMessage'] = e.message if hasattr(e, 'message') else f'{e}'
    
        return jsonify(res), 500
    

提交回复
热议问题