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

时间:2018-10-05 17:18:53

标签: python python-3.x

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

### 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)

基本上,我希望它打印“验证时出错”。我将如何正确执行此操作,或者上述操作是正确的方法?

1 个答案:

答案 0 :(得分:2)

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

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

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