python - 如何继承异常来创建更具体的错误?

标签 python python-2.7 exception inheritance

我正在使用 third party API它会发出 HttpError

通过捕获此错误,我可以检查 http 响应状态并缩小问题范围。所以现在我想发出一个更具体的 HttpError,我将其称为 BackendErrorRatelimitError。后者需要添加上下文变量。

如何创建一个继承自 HttpError 并且可以在不丢失原始异常的情况下创建的自定义异常?

问题实际上是多态101,但我今天脑子很模糊:

class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, ex):
        # super doesn't seem right because I already have
        # the exception. Surely I don't need to extract the
        # relevant bits from ex and call __init__ again?!
        # self = ex   # doesn't feel right either


try:
     stuff()
except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex)

我们如何捕获原始的 HttpError 并将其封装,以便它仍然可以被识别为 HttpError 和 BackendError?

最佳答案

如果你看看 googleapiclient.errors.HttpError 的实际定义,

__init__(self, resp, content, uri=None) 

因此,继承后,您需要使用所有这些值初始化基类。

class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, resp, content, uri=None):
        # Invoke the super class's __init__
        super(BackendError, self).__init__(resp, content, uri)

        # Customization can be done here

然后当你发现错误时,

except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex.resp, ex.content, ex.uri)

如果您不希望客户端显式解压内容,可以在 BackendError__init__ 中接受 HTTPError 对象然后你就可以像这样解包了

class BackendError(HttpError):
    """The Google API is having it's own issues"""
    def __init__(self, ex):
        # Invoke the super class's __init__
        super(BackendError, self).__init__(ex.resp, ex.content, ex.uri)

        # Customization can be done here

然后你就可以简单地做

except HttpError as ex:
     if ex.resp.status == 500:
         raise BackendError(ex)

关于python - 如何继承异常来创建更具体的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29909165/

相关文章:

python - 使用 TrueSkill Algo 回填 Pandas 数据集的最有效方法

python - 选择字符串作为随机种子对输出的影响

c++ - 带有 nothrow 选项的 Operator new 仍然抛出异常

python - 来自元组的任意嵌套字典

python - 在 pandas df 中设置索引而不创建重复列

python - 我尝试django runserver时,Python 2.7突然不起作用:“找不到符号:__ PyErr_ReplaceException”

python - 计算重复列表的频率 - 在列表列表中

Objective-C 堆栈跟踪

python - 如果在 json 转储期间抛出异常,如何避免部分文件?

python - 许多数组的插值的矢量化总和