【问题标题】:How can I debug a Flask application that has a custom exception handler?如何调试具有自定义异常处理程序的 Flask 应用程序?
【发布时间】:2015-03-01 20:10:17
【问题描述】:

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

@application.errorhandler(Exception)
def http_error_handler(error):
    return flask.render_template('error.html', error=error), 500

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

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

【问题讨论】:

    标签: python debugging error-handling flask


    【解决方案1】:

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

    @app.errorhandler(500)
    def handle_internal_error(e):
        return render_template('500.html', error=e), 500
    

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

    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()
    

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

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2018-10-23
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多