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

编程入门 行业动态 更新时间:2024-10-19 14:42:06
我如何为Flask中的所有HTTP错误实现自定义错误处理程序?(How can I implement a custom error handler for all HTTP errors in Flask?)

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

@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错误?

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?

最满意答案

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

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

我并不理解和丑陋,但它会起作用,我确实希望别人能够提供更好的解决方案。 希望这可以帮助。

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.

更多推荐

本文发布于:2023-08-01 18:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1361482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   自定义   何为   程序   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!