33
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.

  1. How do I define these error codes and error messages in the custom exceptions?
  2. 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]])
62

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)

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]))
  • Is there a way to store these error codes and error messages within the custom exceptions? For example, how does this work - except MySQLdb.Error, e: print "%d: %s" % (e.args[0], e.args[1]) ? – Sam May 30 '11 at 19:55 
  • Not completely sure I know what you're asking. I've added an example of possible implementation of what you've shown to my answer. – Bryan May 30 '11 at 20:04
  • 4
    I think you can just make the codes a class property. – Keith May 30 '11 at 20:11
  • Thanks, Bryan. @Keith: Yes, I had a similar idea too - that we might be able to define a dictionary of error codes and error messages within the custom exception classes and access / output that ... – Sam May 30 '11 at 20:22 
  • 2
    If you replace *args with **kwargs you can define argument values by keyword. Example: message="File not found", errorcode="10" – Steven M. Vascellaro Feb 6 '18 at 19:08