如何在 python3 中创建带有错误消息和状态代码的自定义异常

How to create a custom Exception with error message and status code in python3

我正在尝试创建以下异常并在另一个函数中调用它:

### The exception
class GoogleAuthError(Exception):
    def __init__(self, message, code=403):
        self.code = code
        self.message = message

### Generating the exception
raise GoogleAuthError(message="There was an error authenticating")

### printing the exception
try:
    do_something()
except GoogleAuthError as e:
    print(e.message)

基本上,我希望它打印 "There was an error authenticating"。我将如何正确地执行此操作,或者以上是正确的方法吗?

从您的 __init__ 中删除 code 参数。你没有使用它。

您还可以将错误消息的处理委托给父 Exception class,它已经知道消息

class GoogleAuthError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.code = 403

try:
    raise GoogleAuthError('There was an error authenticating')
except GoogleAuthError as e:
    print(e)

# There was an error authenticating