2

I want to be able to return an exception as my lambda response when the flow does not work as expected, so I am doing something like

def handler(event, context):
    try:
        project = event['environment']
    except Exception as ex:
        return {
            'statusCode': 500,
            'body': json.dumps(ex)
        }

However this fails prematurely as in

{"errorMessage": "Object of type KeyError is not JSON serializable", "errorType": "TypeError", "stackTrace": ["  File \"/var/task/hr-management.py\", line 23, in handler\n    'body': json.dumps(ex)\n", "  File \"/var/lang/lib/python3.8/json/__init__.py\", line 231, in dumps\n    return _default_encoder.encode(obj)\n", "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 199, in encode\n    chunks = self.iterencode(o, _one_shot=True)\n", "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 257, in iterencode\n    return _iterencode(o, 0)\n", "  File \"/var/lang/lib/python3.8/json/encoder.py\", line 179, in default\n    raise TypeError(f'Object of type {o.__class__.__name__} '\n"]}%

I have also tried:

def handler(event, context):
    try:
        project = event['environment']
    except Exception as ex:
        return {
            'statusCode': 500,
            'body': ex
        }

Any suggestions?

pkaramol
  • 16,451
  • 43
  • 149
  • 324
  • I think this will help you https://stackoverflow.com/questions/49537095/object-of-type-typeerror-is-not-json-serializable – abdullatif May 16 '21 at 13:33

2 Answers2

2

If you are simply looking for the exception as a string use:

def handler(event, context):
    try:
        project = event['environment']
    except Exception as ex:
        return {
            'statusCode': 500,
            'body': json.dumps(ex.__repr__())
        }

___repr__() returns a string used to format the class for things like print(class_example), it's a readability tool.

ThatOneCoder
  • 116
  • 1
  • 5
0

This is because the exception is not properly defined and is throwing an entire stacktrace you can try making the exception serializable by a small change as quick fix.

Replace json.dumps(ex) with json.dumps(ex.__dict__)

If you want a specific error message, you can try accessing the exception attributes like message or trace.

neeraj mdas
  • 163
  • 3
  • 15
  • I tried this `json.dumps(ex.__dict__)` but it seems empty (?) `{"statusCode": 500, "body": "{}"}` – pkaramol May 16 '21 at 13:44
  • it only avoids the error. If you want to access a particular error message, the exception might have attributes based on the error, like stacktrace, message etc – neeraj mdas May 16 '21 at 13:47
  • If you want to list out all available attributes of your exception you can try printing ```dir(ex)``` and if .msg is available you can use it. But please be mindful that some of these attributes are also non serializable – neeraj mdas May 16 '21 at 13:53
  • if those doesnt work you can also refer https://stackoverflow.com/questions/40422062/api-gateway-lambda-python-handling-exceptions where there is a discussion about lambda specific exception handling – neeraj mdas May 16 '21 at 14:00