社区首页 >问答首页 >带有错误代码和错误消息的自定义Python异常

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

Stack Overflow用户
提问于 2011-05-30 11:41:59
回答 2查看 93K关注 0票数 51
代码语言:javascript
代码运行次数:0
复制
class AppError(Exception):
    pass

class MissingInputError(AppError):
    pass

class ValidationError(AppError):
    pass

..。

代码语言:javascript
代码运行次数:0
复制
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)

input ()和__validateMulti()是验证和存储传递的输入参数的类的方法。正如代码中所显示的那样,当某些输入参数丢失或某些验证失败时,我会引发一些自定义异常。

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

错误1100:“找不到键参数。请验证输入。”

错误1101:“找不到日期参数。请验证您的输入”

..。

错误2100:“多个Day参数无效。接受值为2、5和7。”

并向用户报告同样的情况。

如何在自定义exceptions?

  • How中定义这些错误代码和错误消息?我是否以知道要显示的错误代码/消息的方式引发/捕获异常?

(P.S:这是用于Python2.4.3)。

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

因此,我更喜欢的解决办法是:

代码语言:javascript
代码运行次数:0
复制
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."}

用法:

代码语言:javascript
代码运行次数:0
复制
try:
    # do something here that calls
    # raise MissingInputError(1101)

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-30 11:47:59

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

代码语言:javascript
代码运行次数:0
复制
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,这里还有另外一个例子.

代码语言:javascript
代码运行次数:0
复制
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]))
票数 85
EN

Stack Overflow用户

发布于 2018-05-09 04:29:35

这是我创建的一个使用预定义错误代码的自定义异常的示例:

代码语言:javascript
代码运行次数:0
复制
class CustomError(Exception):
"""
Custom Exception
"""

  def __init__(self, error_code, message='', *args, **kwargs):

      # Raise a separate exception in case the error code passed isn't specified in the ErrorCodes enum
      if not isinstance(error_code, ErrorCodes):
          msg = 'Error code passed in the error_code param must be of type {0}'
          raise CustomError(ErrorCodes.ERR_INCORRECT_ERRCODE, msg, ErrorCodes.__class__.__name__)

      # Storing the error code on the exception object
      self.error_code = error_code

      # storing the traceback which provides useful information about where the exception occurred
      self.traceback = sys.exc_info()

      # Prefixing the error code to the exception message
      try:
          msg = '[{0}] {1}'.format(error_code.name, message.format(*args, **kwargs))
      except (IndexError, KeyError):
          msg = '[{0}] {1}'.format(error_code.name, message)

      super().__init__(msg)


# Error codes for all module exceptions
@unique
class ErrorCodes(Enum):
    ERR_INCORRECT_ERRCODE = auto()      # error code passed is not specified in enum ErrorCodes
    ERR_SITUATION_1 = auto()            # description of situation 1
    ERR_SITUATION_2 = auto()            # description of situation 2
    ERR_SITUATION_3 = auto()            # description of situation 3
    ERR_SITUATION_4 = auto()            # description of situation 4
    ERR_SITUATION_5 = auto()            # description of situation 5
    ERR_SITUATION_6 = auto()            # description of situation 6

枚举ErrorCodes用于定义错误代码。异常的创建方式使传递的错误代码以异常消息为前缀。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6180185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档