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

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

问题描述

在我的 Flask 应用程序中,我可以通过为每个错误代码添加 errorhandler 装饰器来轻松扩展由单个自定义错误处理程序处理的错误列表

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

然而,这种方法需要为每个错误代码显式装饰.有没有办法装饰我的(单个)http_error_handler 函数,以便它处理所有 HTTP 错误?

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?

推荐答案

您不是唯一的一个,一种解决方法是指定您正在捕获并绑定到 application.error_handler_spec 的 http 错误代码列表,然后删除装饰器,如下所示:

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天全站免登陆