skip to Main Content

How do I prevent a Python 3.8 AWS Lambda from logging an unhandled exception?

We have a Python 3.8 AWS Lambda function that is only invoked directly, not via API Gateway or any other AWS service. We have custom logging that formats it correctly for a third party service to consume.

When this lambda has an exception, we want it to fail. Currently the invocation response is:

{
    "StatusCode": 200,
    "FunctionError": "Unhandled",
    "ExecutedVersion": "$LATEST"
}

And the returned payload is:

{
    "errorMessage": "It broke.",
    "errorType": "BrokeError",
    "stackTrace": [
        "many redacted lines...n"
    ]
}

This is great, except when Python crashes, AWS logs this exception using the default AWS logger (which I suspect is stderr), not our custom one. This disrupts integration with our third party log aggregator.

We can wrap the whole lambda function in a try/except and log it explicitly, but we ideally want the "FunctionError": "Unhandled" in the client response. How can this be caused without triggering an automatic error log?

2

Answers


  1. This should allow you guys to respond with HTTP 500 without triggering a crash in the Python runtime.

    import json
    
    def lambda_handler(event, context):
      try:
        # Do work here
    
        return {
            "statusCode": 200,
            "headers": {
                "Content-Type": "application/json"
            },
            "body": json.dumps({})
        }
      except:
        print("An exception occurred")
    
        return {
              "statusCode": 500,
              "headers": {
                  "Content-Type": "application/json"
              },
              "body": json.dumps({})
        }
    
    Login or Signup to reply.
  2. but we ideally want the "FunctionError": "Unhandled" in the client response

    Then handle the error, and put that message in the response:

    def lambda_handler(event, context):
      try:
        # Your current handler code goes here
      except:
        return {
            "statusCode": 500,
            "headers": {
                "Content-Type": "application/json"
            },
            "body": json.dumps({
                "FunctionError": "Unhandled"
            })
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search