gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:32:52 24 4
gpt4 key购买 nike

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

### 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 参数。你没有使用它。

您还可以将错误消息的处理委托(delegate)给父 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

关于python - 如何在 python3 中创建带有错误消息和状态代码的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com