我正在尝试创建以下异常并在另一个函数中调用它:
### 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)
基本上,我希望它打印"身份验证出错"。我将如何正确地执行此操作,或者上述方法是正确的方法?
从__init__
中删除code
参数。 你没有使用它。
您还可以将错误消息的处理委托给父类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