python - 在没有回溯的情况下引发错误

标签 python api wrapper

我想在不在屏幕上打印回溯的情况下使用 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/

相关文章:

javascript - 如何向外部 API 发出 GET 和 POST 请求?

python - Weka:LibSVM 在 GUI 中工作,但不能在带有 WEKA Wrapper 的 Python 代码中工作

python - 将两个 matplotlib figure.Figure 或 axes.Axes 对象合并为一个新对象

python - python 中的 ANSI 编码

javascript - 无法使用 WordPress REST 的 wpapi Node.js 包装器创建自定义字段

f# - 如何在 F# 上制作没有参数的功能包装器?

java - 使用 HTTPServletRequestWrapper 包装请求参数

python - 如何将夹层安装为 Django 应用程序?

python - 分割一串名称

web-services - XML-RPC 是否不好用作公共(public) API 实现的协议(protocol)?