Search code examples
python-3.xlambdaconditional-statementskeyerror

AWS Lambda Error "errorType": "KeyError",


I have python script below in lambda but I am encountering error when testing it.

import json
import boto3
import os
from XXXXXXX import get_client
from datetime import datetime, timedelta
from tabulate import tabulate

client = boto3.client("lambda")

class DateTimeEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return o.isoformat()

        return json.JSONEncoder.default(self, o)


def lambda_handler(event, context):

    client = boto3.client("cloudwatch")
    response = client.get_metric_statistics(
        Namespace="AWS/Lambda",
        MetricName="Errors",
        Dimensions=[{"Name": "FunctionName", "Value": "XXXXXXX"}],
        StartTime=datetime.utcnow() - timedelta(seconds=360),
        EndTime=datetime.utcnow(),
        Period=60,
        Statistics=["Sum"],
    )

    message = json.dumps(response, cls=DateTimeEncoder)
    message2 = json.loads(message)
    message3 = message2["Datapoints"]
    message4 = tabulate(
        message3, headers="keys", tablefmt="psql", numalign="left", stralign="left"
    )
    print(message4)


    error_list = []
    for message2 in message3:
        temp = {}
        if message2["Sum"] > 0:
            temp['There are some errors on QOS Invocations']
        else:
            temp['There are no errors on QOS Invocations']
        error_list.append(temp)
    return error_list
try: 
    error_list = Final_Sum(message2, message3)
    error_list_final = json.dumps(error_list, indent=4, sort_keys=False)
    print(error_list_final)
except Exception as ex:
    print(ex)
    pass

Below is the error encountered. I already tried creating separate function for error_list but encountered same error for "'There are no errors on QOS Invocations'".

{
  "errorMessage": "'There are no errors on QOS Invocations'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/var/task/python/m3ce-getqosAPIerror.py\", line 53, in lambda_handler\n    temp['There are no errors on QOS Invocations']\n"
  ]
}

This works fine when running locally (outside lamdba) and expected output is:

+---------------------------+-------+--------+
| Timestamp                 | Sum   | Unit   |
|---------------------------+-------+--------|
| 2021-01-20T03:49:00+00:00 | 0     | Count  |
| 2021-01-20T03:48:00+00:00 | 0     | Count  |
| 2021-01-20T03:52:00+00:00 | 0     | Count  |
| 2021-01-20T03:51:00+00:00 | 0     | Count  |
| 2021-01-20T03:47:00+00:00 | 0     | Count  |
| 2021-01-20T03:50:00+00:00 | 0     | Count  |
+---------------------------+-------+--------+
'There are no errors on QOS Invocations'

Solution

  • Got explanation for issue here https://realpython.com/python-keyerror