异常子类的打印不是参数元组

Printing of exception subclasses is not a tuple of arguments

项目中使用的例外情况:

class SwitcherError(Exception):
    pass


class ApiError(SwitcherError):
   pass



class ApiHTTPError(ApiError):
    def __init__(self, message=None, text=None, api_errors=None):
        self.text = text
        self.message = message
        self.errors = api_errors


class ApiJsonError(ApiError):
    def __init__(self, message=None, text=None):
        super().__init__(message)
        self.text = text

如果我使用 super 打印出错误,我似乎没有得到参数元组的打印(由 BaseException 定义)但是如果我不使用 super() 并且只是覆盖参数直接在初始化程序中。 我不清楚为什么会这样以及我应该如何编写我的 类.

'text' 输出到哪里了?

try:
    raise ApiJsonError('msg', 'text')
except ApiJsonError as e:
    print(e)
>>> 'msg'

下图符合预期

try:
    raise ApiHTTPError('msg', 'text')
except ApiHTTPError as e:
    print(e)

>>>('msg', 'text')

您可以覆盖 ApiJsonError.__str__:

class ApiJsonError(ApiError):
    def __init__(self, message=None, text=None):
        super().__init__(message)
        self.text = text
    def __str__(self):
        return str((*self.args, self.text))

产生:

>>> try:
...     raise ApiJsonError('msg', 'text')
... except ApiJsonError as e:
...     print(e)
... 
('msg', 'text')

来自docs

The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __str__() so the arguments can be printed directly without having to reference .args.