gpt4 book ai didi

python - 带有错误代码和错误消息的自定义 Python 异常

转载 作者:IT老高 更新时间:2023-10-28 21:47:10 30 4
gpt4 key购买 nike

class AppError(Exception):
pass

class MissingInputError(AppError):
pass

class ValidationError(AppError):
pass

...

def validate(self):
""" Validate Input and save it """

params = self.__params

if 'key' in params:
self.__validateKey(escape(params['key'][0]))
else:
raise MissingInputError

if 'svc' in params:
self.__validateService(escape(params['svc'][0]))
else:
raise MissingInputError

if 'dt' in params:
self.__validateDate(escape(params['dt'][0]))
else:
raise MissingInputError


def __validateMulti(self, m):
""" Validate Multiple Days Request"""

if m not in Input.__validDays:
raise ValidationError

self.__dCast = int(m)

validate() 和 __validateMulti() 是验证和存储传递的输入参数的类的方法。从代码中可以看出,当某些输入参数丢失或某些验证失败时,我会引发一些自定义异常。

我想定义一些特定于我的应用的自定义错误代码和错误消息,例如,

Error 1100: "Key parameter not found. Please verify your input."

Error 1101: "Date parameter not found. Please verify your input"

...

Error 2100: "Multiple Day parameter is not valid. Accepted values are 2, 5 and 7."

并向用户报告。

  1. 如何在自定义异常中定义这些错误代码和错误消息?
  2. 如何以我知道要显示什么错误代码/消息的方式引发/捕获异常?

(PS:这是针对 Python 2.4.3)。


Bastien Léonard 在 SO comment 中提到你不需要总是定义一个新的 __init____str__;默认情况下,参数将放在 self.args 中,并由 __str__ 打印。

因此,我更喜欢的解决方案:

class AppError(Exception): pass

class MissingInputError(AppError):

# define the error codes & messages here
em = {1101: "Some error here. Please verify.", \
1102: "Another here. Please verify.", \
1103: "One more here. Please verify.", \
1104: "That was idiotic. Please verify."}

用法:

try:
# do something here that calls
# raise MissingInputError(1101)

except MissingInputError, e
print "%d: %s" % (e.args[0], e.em[e.args[0]])

最佳答案

这是一个带有特殊代码的自定义 Exception 类的快速示例:

class ErrorWithCode(Exception):
def __init__(self, code):
self.code = code
def __str__(self):
return repr(self.code)

try:
raise ErrorWithCode(1000)
except ErrorWithCode as e:
print("Received error with code:", e.code)

既然您问的是如何使用 args,这里还有一个示例...

class ErrorWithArgs(Exception):
def __init__(self, *args):
# *args is used to get a list of the parameters passed in
self.args = [a for a in args]

try:
raise ErrorWithArgs(1, "text", "some more text")
except ErrorWithArgs as e:
print("%d: %s - %s" % (e.args[0], e.args[1], e.args[2]))

关于python - 带有错误代码和错误消息的自定义 Python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6180185/

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