gpt4 book ai didi

python - 更改 python 中未捕获异常处理的默认行为

转载 作者:太空狗 更新时间:2023-10-30 02:21:00 25 4
gpt4 key购买 nike

我经历了“Logging uncaught exceptions in Python”。而且,我试过这个:

import web
import sys

app = web.application((
'/test', 'test'), globals())

def test_func(e_type, value, traceback):
print "Handled exception here.."

class test:
def GET(self):
a = 1/0

if __name__ == "__main__":
sys.excepthook = test_func
app.run()

在这里,你可以很容易地看到是否有GET/test请求进来,我是故意抛出ZerDivisionError。因为我已经重写了 sys.excepthook,所以我希望方法 test_funcZeroDivisionError 上执行。

然而,这段代码没有按预期工作。我观察到,当我尝试在独立代码(而不是网络应用程序)中覆盖 excepthook 时,它工作正常。正确调用新方法(覆盖)。

知道为什么会出现这种不同的行为吗?

最佳答案

使用 web.py,自己捕获异常的一种方法是 add a custom processor :

...
def error_processor(handler):
try:
handler()
except:
# do something reasonable to handle the exception
return 'something happened...'

app.add_processor(error_processor)
app.run()
...

否则 web.py 将捕获异常并显示默认错误消息。

关于python - 更改 python 中未捕获异常处理的默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18810993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com