Python 如何从异常继承以创建更具体的错误?
我使用的是发出Python 如何从异常继承以创建更具体的错误?,python,python-2.7,exception,inheritance,Python,Python 2.7,Exception,Inheritance,我使用的是发出HttpError的 通过捕获此错误,我可以检查http响应状态并缩小问题范围。所以现在我想发出一个更具体的HttpError,我将其命名为BackendError和RatelimitError。后者具有要添加的上下文变量 如何创建从HttpError继承的自定义异常,并且可以在不丢失原始异常的情况下创建该异常 问题其实很复杂,但我今天的头脑很模糊: class BackendError(HttpError): """The Google API is having it'
HttpError
的
通过捕获此错误,我可以检查http响应状态并缩小问题范围。所以现在我想发出一个更具体的HttpError,我将其命名为BackendError
和RatelimitError
。后者具有要添加的上下文变量
如何创建从HttpError继承的自定义异常,并且可以在不丢失原始异常的情况下创建该异常
问题其实很复杂,但我今天的头脑很模糊:
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?如果您查看 因此,在继承之后,您需要使用所有这些值初始化基类
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
的\uuuu init\uuuuuuuu
中的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)
哦,对不起。我更关注的是不完整的
BackendError
。哪个Python版本?2.7和3.x具有特殊形式的raise
语句,可以在保留原始回溯对象的同时更改异常类。在早期版本中,我认为您要么在退出时对异常进行变异(比如,如果您只想编辑属性),要么在旧的基础上创建一个新的异常,但在这个过程中丢失了完整的回溯。是的,不幸的是,它在python 2上。7@PeterDeGlopper你能告诉我们更多吗?我在考虑2.7的三参数形式raise
:-但是如果3.x风格的异常链接是一件你可以做的事情,那么它显然会更好。
except HttpError as ex:
if ex.resp.status == 500:
raise BackendError(ex)