Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Python Exceptions with Error Codes and Error Messages

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]]) 
like image 846
Sam Avatar asked May 30 '11 19:05

Sam


People also ask

How do I create a custom error in Python?

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

Can you throw custom exception with error object?

While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object.

What are the 3 major exception types in Python?

There are mainly three kinds of distinguishable errors in Python: syntax errors, exceptions and logical errors.

What are errors and exceptions in Python programs?

Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. Two types of Error occurs in python.


1 Answers

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])) 
like image 114
Bryan Avatar answered Oct 05 '22 07:10

Bryan