如何调试具有自定义异常处理程序的 Flask 应用程序?

oro*_*ome 5 python debugging error-handling flask

我想为我的 Flask 应用程序实现一个异常处理程序,当Exception抛出an 时显示自定义错误页面。我可以轻松地使用它

@application.errorhandler(Exception)
def http_error_handler(error):
    return flask.render_template('error.html', error=error), 500
Run Code Online (Sandbox Code Playgroud)

但这具有在异常到达调试器(Werkzeug 调试器或我的 IDE)之前捕获所有异常的副作用,以便有效地禁用调试。

如何实现仍然允许调试异常和错误的自定义异常处理程序?有没有办法在调试模式下禁用我的自定义处理程序?

dav*_*ism 6

当未捕获的异常传播时,Werkzeug 将生成 500 异常。为500而非为创建错误处理程序Exception。启用调试时会绕过 500 处理程序。

@app.errorhandler(500)
def handle_internal_error(e):
    return render_template('500.html', error=e), 500
Run Code Online (Sandbox Code Playgroud)

以下是一个完整的应用程序,它演示了错误处理程序适用于断言、引发和中止。

from flask import Flask, abort

app = 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()
Run Code Online (Sandbox Code Playgroud)

转到所有三个 url(/assert、/raise 和 /abort)将显示消息“出现错误”。运行 withapp.run(debug=True)只会显示 /abort 的消息,因为这是一个“预期的”响应;其他两个 url 将显示调试器。