带有错误代码和错误消息的自定义

带有错误代码和错误消息的自定义

本文介绍了带有错误代码和错误消息的自定义 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() 是用于验证和存储传递的输入参数的类的方法.从代码中可以明显看出,当缺少某些输入参数或某些验证失败时,我会引发一些自定义异常.

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,

错误 1100:未找到关键参数.请验证您的输入."

错误 1101:未找到日期参数.请验证您的输入"

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

...

错误 2100:多日参数无效.可接受的值为 2、5 和 7."

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

并向用户报告相同的内容.

and report the same to the user.

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

(PS:这适用于 Python 2.4.3).

Bastien Léonard 在这个SO评论中提到你需要始终定义一个新的 __init____str__;默认情况下,参数将放置在 self.args 中,它们将通过 __str__ 打印.

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."}

用法:

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

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

推荐答案

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

Here's a quick example of a custom Exception class with special codes:

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,这里有一个额外的例子......

Since you were asking about how to use args here's an additional example...

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 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:15