我想在不在屏幕上打印回溯的情况下使用 raise
。我知道如何使用 try ..catch
来做到这一点,但找不到使用 raise
的方法。
这是一个例子:
def my_function(self):
resp = self.resp
if resp.status_code == 404:
raise NoSuchElementError('GET'+self.url+'{}'.format(resp.status_code))
elif resp.status_code == 500:
raise ServerErrorError('GET'+self.url+'{}'.format(resp.status_code))
执行此操作时,如果出现 404,回溯将打印在屏幕上。
Traceback (most recent call last):
File "test.py", line 32, in <module>
print ins.my_function()
File "api.py", line 820, in my_function
raise NoSuchElementError('GET ' + self.url + ' {} '.format(resp.status_code))
这是一个 API 包装器,我不希望用户看到回溯,而是看到 API 响应代码和错误消息。
有办法吗?
最佳答案
我遇到了一个类似的问题,父类在 raise
上使用异常值来传递消息,但我不想转储回溯。 @lejlot 使用 sys.excepthook
提供了一个很好的解决方案,但我需要在更有限的范围内应用它。这是修改:
import sys
from contextlib import contextmanager
@contextmanager
def except_handler(exc_handler):
"Sets a custom exception handler for the scope of a 'with' block."
sys.excepthook = exc_handler
yield
sys.excepthook = sys.__excepthook__
然后,使用它:
def my_exchandler(type, value, traceback):
print(': '.join([str(type.__name__), str(value)]))
with except_handler(my_exchandler):
raise Exception('Exceptional!')
# -> Exception: Exceptional!
这样,如果 block 中没有引发异常,默认异常处理将为任何后续异常恢复:
with except_handler(my_exchandler):
pass
raise Exception('Ordinary...')
# -> Traceback (most recent call last):
# -> File "raise_and_suppress_traceback.py", line 22, in <module>
# -> raise Exception('Ordinary...')
# -> Exception: Ordinary...
关于python - 在没有回溯的情况下引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38598740/