如何在Flask中实现所有HTTP错误的自定义错误处理程序? [英] How can I implement a custom error handler for all HTTP errors in Flask?

查看:177
本文介绍了如何在Flask中实现所有HTTP错误的自定义错误处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Flask应用程序中,我可以轻松地扩展单个自定义错误处理程序处理的错误列表,方法是对每个错误代码添加

添加 errorhandler

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

但是,这种方法需要对每个错误代码进行显式装饰。有没有办法装饰我的(单) http_error_handler 函数,以便它处理所有 HTTP错误?

解决方案

您不是唯一的解决方法,一个解决方法将指定您捕获并绑定到 application.error_handler_spec ,并删除装饰器,如下所示:

  def http_error_handler(error):
return flask.render_template (401,404,500)中的错误:#或与您认为错误的其他http代码
application.error_handler_spec [没有] [错误] = http_error_handler

不理想和丑陋我知道,但它会工作,我做希望别人能有更好的解决方案。希望这有帮助。


In my Flask app, I can easily expand the list of errors handled by a single custom error handler by adding errorhandler decorators for each error code as with

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

However this approach requires an explicit decorator for each error code. Is there a way decorate my (single) http_error_handler function so that it handles all HTTP errors?

解决方案

You're not the only one, one workaround will be specifying the list of the http error code you're catching and bound to application.error_handler_spec, and drop the decorators, like this:

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

for error in (401, 404, 500): # or with other http code you consider as error
    application.error_handler_spec[None][error] = http_error_handler

Not ideal and ugly I know, but it will work and I do hope someone else can come with a better solution. Hope this helps.

这篇关于如何在Flask中实现所有HTTP错误的自定义错误处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆