我在为 Python Web API 设计异常类时遇到了一些麻烦。我想做的是使用一些默认错误代码/消息设置各种异常,但也允许灵活地创建自定义异常。
采用以下代码:
class APIException(Exception):
def __init__(self):
super().__init__(self.message)
@property
def message(self) -> str:
raise NotImplementedError
@property
def code(self) -> int:
raise NotImplementedError
@property
def response(self):
return {"error": self.message}, self.code
class UnknownException(APIException):
message = "An unknown error occurred."
code = 500
class UnauthorizedException(APIException):
message = "Unauthorized"
code = 401
这使我可以执行诸如raise UnauthorizedException
之类的操作,效果很好。
但是,我希望能够引发任意 API 异常,例如引发 APIException("这是自定义错误", 404)。不需要支持引发带参数的设置异常和引发不带参数的 APIException
;我不会那样抚养他们。
我似乎无法用上面设计继承的方式干净地做到这一点。我尝试过其他各种方法,但似乎没有一个像上面的示例那么干净。
做这类事情的最佳方法是什么?
最佳答案
让您的 APIException
构造函数接受参数,并让子类实现提供这些参数的构造函数:
class APIException(Exception):
def __init__(self, message, code):
super().__init__(message)
self.message = message
self.code = code
@property
def response(self):
return {"error": self.message}, self.code
class UnknownException(APIException):
def __init__():
super().__init__("An unknown error occurred.", 500)
class UnauthorizedException(APIException):
def __init__():
super().__init__("Unauthorized", 401)
关于python - 设计异常继承的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490192/