Exception (python)

Try-catch-finally with stacktrace

lambda_function.py

import app.exc

from app_generic import ag_log_exception


def lambda_handler(event, context):

ret = {}


try:

print('Hello')

raise app.exc.AppRestExc(203, '{valid: false}')

print('Should not be printed')

except Exception as e:

ag_log_exception('EXC MAIN_TRY_CATCH', e)

finally:

# Return

return ret


app_generic

import logging

import os

import sys

import traceback


# Logger

logger = logging.getLogger()

logger.setLevel(logging.INFO)



""" Log exception

:param prefix: Literal pre-apended to the log output

:param e: Exception

:returns: Void

"""

def ag_log_exception(prefix, e):

exc_type, exc_obj, exc_tb = sys.exc_info()

fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]

logger.error('%s: %s\nType: %s\nFile: %s\nLine: %s\n', prefix, str(e), exc_type, fname, exc_tb.tb_lineno)

traceback.print_exc()



Custom exception hierarchy

app/exc.py

""" Custom BASE exception

"""

class AppBaseExc(Exception):

def __init__(self, *args):

super(AppBaseExc, self).__init__(args)




""" Custom REST exception

"""

class AppRestExc(AppBaseExc):

def __init__(self, status_code, body=None):

super(AppRestExc, self).__init__(status_code, body)

self.status_code = status_code

self.body = body


def __str__(self):

if self.body:

return 'AppRestEx: {0} {1}'.format(self.status_code, self.body)

else:

return 'AppRestEx: {0}'.format(self.status_code)


""" Raise exception if REST response error

:param rest_response The REST response

:returns: Void

"""

@staticmethod

def raise_if_rest_error(rest_response):

if not(200 <= rest_response.status_code and rest_response.status_code < 300):

raise AppRestExc(rest_response.status_code, rest_response.text)





""" Custom SOAP exception

"""

class AppSoapExc(AppBaseExc):

def __init__(self, status_code, body=None):

super(AppSoapExc, self).__init__(status_code, body)

self.status_code = status_code

self.body = body


def __str__(self):

if self.body:

return 'AppSoapEx: {0} {1}'.format(self.status_code, self.body)

else:

return 'AppSoapEx: {0}'.format(self.status_code)


""" Raise exception if SOAP response error

:param http_response The HTTP response

:returns: Void

:throws -

"""

@staticmethod

def raise_if_soap_error(http_response):

if not(200 <= http_response.status_code and http_response.status_code < 300):

raise AppSoapExc(http_response.status_code, http_response.text)



Usage: AppRestExc.raise_if_rest_error

logger.info('INI BBC getUserByExtId(%s)', u_code)

http_res = requests.request(method, url, headers=headers)

logger.info('END BBC getUserByExtId(%s):\n%s', u_code, http_res.text)


app.exc.AppRestExc.raise_if_rest_error(http_res)