« Back to Index

[Python Custom Exception Handling]

View original Gist on GitHub

Tags: #python #custom #exceptions #error #handling

Python Custom Exception Handling.py

class CustomError(Exception):
	def __init__(self, exc='exception raised', code=500):
		super().__init__(exc)
		self.code = code
        
    # not needed, but can help when represented as a string
    def __str__(self):
        return f'uh-oh the error code is: {self.code}'
        
class NewCustomError(CustomError):
	pass

try:
	raise CustomError('a thing happened', code=400)
except CustomError as err:
	logging.error(f'msg: {err}, code: {err.code}')

ERROR:root:msg: a thing happened, code: 400

try:
	raise NewCustomError()
except NewCustomError as err:
	logging.error(f'msg: {err}, code: {err.code}')

ERROR:root:msg: exception raised, code: 500


"""
From outside a try/except, use `gen_exc` as a naming convention instead of `exc`
This will avoid linting concerns...

    try:
        response_data = json.loads(response.body)
    except Exception as exc:
        msg = 'JSON_PARSING_FAILED'
        log_exception(exc, msg, body=response.body)
        raise exceptions.CognitoException(msg, code=extract_status_code(exc))

    if response_data.get('error'):
        msg = 'TOKEN_EXCHANGE_FAILED'
        gen_exc = exceptions.CognitoException(msg)
        log_exception(gen_exc, msg, context=response_data.get('error'))
        raise gen_exc
"""




# basic

class ArgumentError(Exception):
    pass

def foo(x):
    if x == 123:
        raise ArgumentError("doh!")

# much more 'custom'

if True:
  raise CustomError('thing')
  
class CustomError(Exception):
    '''
    This does stuff
    '''
    def __init__(self, thing):
        super().__init__('something went wrong')
        self.thing = thing