How can I debug a Flask application that has a custom exception handler?
Werkzeug will generate a 500 exception when an uncaught exception propagates. Create an error handler for 500
, not for Exception
. The 500 handler is bypassed when debugging is enabled.
@app.errorhandler(500)def handle_internal_error(e): return render_template('500.html', error=e), 500
The following is a full app that demonstrates that the error handler works for assert, raise, and abort.
from flask import Flask, abortapp = Flask(__name__)@app.errorhandler(500)def handle_internal_error(e): return 'got an error', 500@app.route('/assert')def from_assert(): assert False@app.route('/raise')def from_raise(): raise Exception()@app.route('/abort')def from_abort(): abort(500)app.run()
Going to all three urls (/assert, /raise, and /abort) will show the message "got an error". Running with app.run(debug=True)
will only show the message for /abort since that is an "expected" response; the other two urls will show the debugger.