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]])