如何拦截flask中的所有异常? [英] How to intercept all exceptions in flask?
问题描述
也许我在文档中没有看到任何内容.
Perhaps I am not seeing something in the documentation.
我不仅要处理一些 http 错误,还要处理所有异常.原因 - 我想使用我自己的自定义逻辑来记录它们(听起来像是重新发明轮子,但我需要完全控制日志记录.我不想让服务器屈服于异常,而是只轰炸那个特定的请求.
I would like to not just handle some http errors, but all exceptions. The reason - I would like to log them using my own custom logic (sounds like reinventing the wheel, but I need full control over logging. I would like to not bring the server to its knees upon an exception, but bomb only that particular request.
这就是我现在启动 Flask 的方式.这里 app.run
启动服务器.我如何指示它在发生异常时调用我的异常处理程序方法?
This is how I launch Flask now. Here app.run
starts the server. How can I instruct it to call my exception handler method whenever an exception occurs?
def main():
args = parse_args()
app.config['PROPAGATE_EXCEPTIONS'] = True
flask_options = {'port' : args.port}
if args.host == 'public':
flask_options['host'] = '0.0.0.0'
app.run(**flask_options)
if __name__ == '__main__':
_sys.exit(main())
推荐答案
你应该使用 errorhandler
,参见文档 http://flask.pocoo.org/docs/patterns/errorpages/#error-handlers 和 http://flask.pocoo.org/docs/api/#flask.Flask.errorhandler.它允许您获得调度程序中引发的所有异常,但不能处理错误处理程序中的异常.例如处理所有异常:
You should use errorhandler
, see documentation http://flask.pocoo.org/docs/patterns/errorpages/#error-handlers and http://flask.pocoo.org/docs/api/#flask.Flask.errorhandler. It is allow you get all exceptions raised in dispatchers, but not handle exceptions in error handlers. For example to handle all exceptions:
@app.errorhandler(Exception)
def all_exception_handler(error):
return 'Error', 500
在这种情况下,我更喜欢显式异常处理程序还是使用装饰器(基于类的视图).
How ever I prefer explicit exceptions handlers or use decorators (class based views) for this cases.
这篇关于如何拦截flask中的所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!