我正在尝试创建以下异常并在另一个函数中调用它:
### 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)
基本上,我希望它打印“验证时出错”。我将如何正确执行此操作,或者上述操作是正确的方法?
答案 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