带有错误代码和错误消息的自定义 Python 异常
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() 是验证和存储传递的输入参数的类的方法。从代码中可以明显看出,当某些输入参数丢失或某些验证失败时,我会引发一些自定义异常。
我想定义一些特定于我的应用程序的自定义错误代码和错误消息,例如,
错误 1100:“未找到关键参数。请验证您的输入。”
错误 1101:“未找到日期参数。请验证您的输入”
...
错误 2100:“多日参数无效。接受的值为 2、5 和 7。”
并向用户报告相同的情况。
- 如何在自定义异常中定义这些错误代码和错误消息?
- 如何以知道要显示什么错误代码/消息的方式引发/捕获异常?
(PS:这是针对 Python 2.4.3 的)。
Bastien Léonard 在此 SO 评论中提到 你不需要总是需要定义一个新的__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]])
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() and __validateMulti() are methods of a class that validates and store the passed input parameters. As is evident in the code, I raise some custom exceptions when some input parameter is missing or some validation fails.
I'd like to define some custom error codes and error messages specific to my app like,
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."
and report the same to the user.
- How do I define these error codes and error messages in the custom exceptions?
- How do I raise / trap exception in a way that I know what error code / message to display?
(P.S: This is for Python 2.4.3).
Bastien Léonard mentions in this SO comment that you don't need to always define a new __init__
or __str__
; by default, arguments will be placed in self.args and they will be printed by __str__
.
Thus, the solution I prefer:
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."}
Usage:
try:
# do something here that calls
# raise MissingInputError(1101)
except MissingInputError, e
print "%d: %s" % (e.args[0], e.em[e.args[0]])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是带有特殊代码的自定义
Exception
类的快速示例:既然您询问如何使用
args
,这里有一个附加示例...Here's a quick example of a custom
Exception
class with special codes:Since you were asking about how to use
args
here's an additional example...这是我创建的自定义异常的示例,它使用预定义的错误代码:
枚举 ErrorCodes 用于定义错误代码。
异常的创建方式是将传递的错误代码作为异常消息的前缀。
This is an example of a custom exception I created which makes use of pre-defined error codes:
The enum ErrorCodes is used to define error codes.
The exception is created in such a way that the error code passed is prefixed to the exception message.