我正在使用发出HttpErrorthird party API

通过捕获此错误,我可以检查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)




如果您不希望客户端显式解压缩内容,则可以接受HTTPErrorBackendError中的__init__对象,然后可以进行解压缩,如下所示

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)

09-08 03:20