[英]Flask and sys.excepthook
I want to add global exception handling object to my Flask webproject. 我想将全局异常处理对象添加到我的Flask Web项目中。 In main module, where application class is created I've added code to override sys.excepthook
. 在创建应用程序类的主模块中,我添加了代码以覆盖sys.excepthook
。 Here is simple test code: 这是简单的测试代码:
import sys
def my_exception_hook(exception_type, value, traceback):
print "My exception handler"
print " Exception type:", exception_type
print " Exception instance:", value
print " Traceback:", traceback
sys.__excepthook__(exception_type, value, traceback)
sys.excepthook = my_exception_hook
from flask import Flask
import requests
app = Flask(__name__)
@app.route('/')
def index():
#Exception raised here "requests.exceptions.MissingSchema" not captured by my handler
r = requests.get('ololo', auth=('user', 'pass'))
return "Hello, world!"
#raise Exception("AAA") #Exception raised here is successfully goes to my_exception_hook
app.run(debug=True, port=5001)
I do not want and have no possibility to envelop each call or requests
module with try/catch
. 我不希望也没有可能用try/catch
包围每个调用或requests
模块。 Also I want to handle other eaception, for example, mongoDB connection problem which may occured spontaneousely (not wheen I creating connection), please do not suggest it. 另外,我还想处理其他方法,例如mongoDB连接问题,它可能是自发发生的(不是在我创建连接时发生的),请不要提出它。
Flask already handles exceptions in views for you. Flask已经为您处理了视图中的异常。 Using sys.excepthook
is not the right way to handle this, the hook will never be called. 使用sys.excepthook
不是正确的处理方式,因此永远不会调用该钩子。
Specify a custom exception handler with Flask instead, see the Redirects and Errors section of the Quickstart manual: 请使用Flask指定一个自定义异常处理程序,请参见快速入门手册的“ 重定向和错误”部分 :
from flask import render_template
@app.errorhandler(500)
def page_not_found(error):
return 'some error message'
Flask also uses the logging
module to record exceptions; Flask还使用logging
模块记录异常。 configure the logging module to write anything of severity logging.ERROR
to the console or a log file. 配置日志记录模块以将任何严重性日志记录logging.ERROR
写入控制台或日志文件。
Since you use app.run(debug=True, port=5001)
, you'll already see exceptions printed to the console. 由于您使用app.run(debug=True, port=5001)
,因此您已经可以看到打印到控制台的异常。
Note that the 500 error page is only ever invoked when debug is not set to True
however; 请注意,只有在debug 未设置为True
时,才调用500错误页面。 otherwise the Werkzeug debug view is invoked instead. 否则,将调用Werkzeug调试视图 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.