Reputation: 21178
Is there any way in Flask to create a custom function for an unhanded exception? My real goal is to log the exception and return an HTTP 500 whenever something happens that is unexpected.
# Modules
app = Flask(__name__)
app.handle_exception = lambda e: 'exception!'
Upvotes: 2
Views: 3196
Reputation: 127410
Decorate a function with app.errorhandler
. This route will take the exception raised, and should return a response like any other route. Note that you need to return the right http status code as part of the response.
Error handlers can handle status codes as well. The 500 status will be raised by Flask on unhandled exceptions, so you can add a handler for that.
@app.errorhandler(500)
def handle_internal_server_error(e):
return render_template('500.html'), 500
Note that if you have the Werkzeug debugger enabled, such as with app.run(debug=True)
or a few other ways, the debugger will handle internal errors before your custom 500 error handler.
Upvotes: 6