Custom Python Exceptions with Error Codes and Error Messages Custom Python Exceptions with Error Codes and Error Messages python python

Custom Python Exceptions with Error Codes and Error Messages


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


This is an example of a custom exception I created which makes use of pre-defined error codes:

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@uniqueclass 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

The enum ErrorCodes is used to define error codes.The exception is created in such a way that the error code passed is prefixed to the exception message.