如何在Flask中实现所有HTTP错误的自定义错误处理程序? [英] How can I implement a custom error handler for all HTTP errors in 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屋!