Python 设计异常继承的标准方法是什么?
我在为PythonWebAPI设计异常类时遇到了一些麻烦。我想做的是用一些默认的错误代码/消息设置各种异常,但也允许灵活地创建一个自定义的异常 以下面的代码为例:Python 设计异常继承的标准方法是什么?,python,python-3.x,oop,inheritance,Python,Python 3.x,Oop,Inheritance,我在为PythonWebAPI设计异常类时遇到了一些麻烦。我想做的是用一些默认的错误代码/消息设置各种异常,但也允许灵活地创建一个自定义的异常 以下面的代码为例: class APIException(Exception): def __init__(self): super().__init__(self.message) @property def message(self) -> str: raise NotImplement
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
这让我可以做一些事情,比如引发未经授权的异常
,这很好。
但是,我希望能够引发任意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)