gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:05 25 4
gpt4 key购买 nike

我正在使用 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/

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