TAGS :Viewed: 7 - Published at: a few seconds ago

[ How can I debug a Flask application that has a custom exception handler? ]

I would like to implement an exception handler for my Flask application that displays a custom error page when an Exception is thrown. I can get this working easily with

def http_error_handler(error):
    return flask.render_template('error.html', error=error), 500

but this has the side effect of catching all exceptions before they hit the debugger (either the Werkzeug debugger or my IDE's) so that debugging is effectively disabled.

How can I implement a custom exception handler that still allows be to debug exceptions and errors? Is there a way to disable my custom handler when in debug mode?

Answer 1

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.

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, abort

app = Flask(__name__)

def handle_internal_error(e):
    return 'got an error', 500

def from_assert():
    assert False

def from_raise():
    raise Exception()

def from_abort():


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.