Skip to content

Instantly share code, notes, and snippets.

@SQLadmin
Last active October 2, 2018 03:58
Show Gist options
  • Save SQLadmin/497b64cf52fe1c47f1b93688e6c13bdf to your computer and use it in GitHub Desktop.
Save SQLadmin/497b64cf52fe1c47f1b93688e6c13bdf to your computer and use it in GitHub Desktop.
lambda error
# my code
from __future__ import print_function
import json
import sys
import os
print('Loading function')
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
message = event['Records'][0]['Sns']['Message']
message = json.loads(message.replace('\"', '"'))
print(message.__class__.__name__)
###### print(event) #######
{u'Records': [{u'EventVersion': u'1.0', u'EventSubscriptionArn': u'arn:aws:sns:us-east-1:612700004603:bhuvi:be1e25bf-a010-42f7-af2a-26755890f131', u'EventSource': u'aws:sns', u'Sns': {u'SignatureVersion': u'1', u'Timestamp': u'2018-01-14T06:47:36.743Z', u'Signature': u'SwkRF2nYL911VDR9kT17fPViHBgHP5d1jt+CzAVlwfCXwxRYSg1iwPZWltCIhmAmjMbzGJUmC1qflbFLjKhKwMFhV4E6ePbsGH720BSiX4ZJmomjvl8OkNfU5Yxcw0U1SuTEUbXNhK9+3z28rNutDYmzIoUWunAUg1wUyXdhOQiwkrrfaUdmiipJPliZrp/2uVGvVp96ZSaoSp+PZdSvUOlkUzceSllnjTOqrLiywUapjkpwV7GEn2wJTuKy1VtaJXOLqoyjHfW1BY5PCSAq46s8h492Vq02uHMycGsuQgvPVC48SeVxd9DVronGKg6jgWhu2jbqWoJj3LJ9xwI7WA==', u'SigningCertUrl': u'https://sns.us-east-1.amazonaws.com/SimpleNotificationService-433026a4050d206028891664da859041.pem', u'MessageId': u'5a6af4cf-ba8a-5598-8260-a61b45c21737', u'Message': u'{"AlarmName":"test","AlarmDescription":"test","AWSAccountId":"612700004603","NewStateValue":"ALARM","NewStateReason":"Threshold Crossed: 1 out of the last 1 datapoints [2.634887005644825 (14/01/18 06:42:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for OK -> ALARM transition).","StateChangeTime":"2018-01-14T06:47:36.708+0000","Region":"US East (N. Virginia)","OldStateValue":"OK","Trigger":{"MetricName":"CPUUtilization","Namespace":"AWS/RDS","StatisticType":"Statistic","Statistic":"AVERAGE","Unit":null,"Dimensions":[{"name":"DBInstanceIdentifier","value":"powercloud-tools01"}],"Period":300,"EvaluationPeriods":1,"ComparisonOperator":"GreaterThanOrEqualToThreshold","Threshold":1.0,"TreatMissingData":"","EvaluateLowSampleCountPercentile":""}}', u'MessageAttributes': {}, u'Type': u'Notification', u'UnsubscribeUrl': u'https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:612700004603:bhuvi:be1e25bf-a010-42f7-af2a-26755890f131', u'TopicArn': u'arn:aws:sns:us-east-1:612700004603:bhuvi', u'Subject': u'ALARM: "test" in US East (N. Virginia)'}}]}
## results while executing
Response:
{
"stackTrace": [
[
"/var/task/lambda_function.py",
13,
"lambda_handler",
"message = json.loads(message.replace('\\\"', '\"'))"
],
[
"/usr/lib64/python2.7/json/__init__.py",
339,
"loads",
"return _default_decoder.decode(s)"
],
[
"/usr/lib64/python2.7/json/decoder.py",
364,
"decode",
"obj, end = self.raw_decode(s, idx=_w(s, 0).end())"
],
[
"/usr/lib64/python2.7/json/decoder.py",
382,
"raw_decode",
"raise ValueError(\"No JSON object could be decoded\")"
]
],
"errorType": "ValueError",
"errorMessage": "No JSON object could be decoded"
}
Request ID:
"c75913f0-f8f1-11e7-b4d7-e5e741b9eb9a"
Function Logs:
START RequestId: c75913f0-f8f1-11e7-b4d7-e5e741b9eb9a Version: $LATEST
No JSON object could be decoded: ValueError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 13, in lambda_handler
message = json.loads(message.replace('\"', '"'))
File "/usr/lib64/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
END RequestId: c75913f0-f8f1-11e7-b4d7-e5e741b9eb9a
REPORT RequestId: c75913f0-f8f1-11e7-b4d7-e5e741b9eb9a Duration: 17.46 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 19 MB
@SQLadmin
Copy link
Author

Now Im getting this error

Response:
{
"errorMessage": "Expecting value: line 1 column 1 (char 0)",
"errorType": "JSONDecodeError",
"stackTrace": [
[
"/var/task/lambda_function.py",
7,
"lambda_handler",
"message = json.loads(event['Records'][0]['Sns']['Message'])"
],
[
"/var/lang/lib/python3.6/json/init.py",
354,
"loads",
"return _default_decoder.decode(s)"
],
[
"/var/lang/lib/python3.6/json/decoder.py",
339,
"decode",
"obj, end = self.raw_decode(s, idx=_w(s, 0).end())"
],
[
"/var/lang/lib/python3.6/json/decoder.py",
357,
"raw_decode",
"raise JSONDecodeError("Expecting value", s, err.value) from None"
]
]
}

Request ID:
"cd0cb0be-f8fb-11e7-8d3c-41b9ffe291bd"

Function Logs:
START RequestId: cd0cb0be-f8fb-11e7-8d3c-41b9ffe291bd Version: $LATEST
{'Records': [{'EventVersion': '1.0', 'EventSubscriptionArn': 'arn:aws:sns:EXAMPLE', 'EventSource': 'aws:sns', 'Sns': {'SignatureVersion': '1', 'Timestamp': '1970-01-01T00:00:00.000Z', 'Signature': 'EXAMPLE', 'SigningCertUrl': 'EXAMPLE', 'MessageId': '95df01b4-ee98-5cb9-9903-4c221d41eb5e', 'Message': 'Hello from SNS!', 'MessageAttributes': {'Test': {'Type': 'String', 'Value': 'TestString'}, 'TestBinary': {'Type': 'Binary', 'Value': 'TestBinary'}}, 'Type': 'Notification', 'UnsubscribeUrl': 'EXAMPLE', 'TopicArn': 'arn:aws:sns:EXAMPLE', 'Subject': 'TestInvoke'}}]}
Expecting value: line 1 column 1 (char 0): JSONDecodeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 7, in lambda_handler
message = json.loads(event['Records'][0]['Sns']['Message'])
File "/var/lang/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

@juancho088
Copy link

That's because now the event is different, you need to evaluate that cases (that's why I said that is important to use .get() function with dicts). The solution could be this

    message = event['Records'][0]['Sns']['Message']
    if isinstance(message, str):
        try:
            message = json.loads(message)
        except Exception as e:
            print(e)
    elif isinstance(message, list):
        message = message[0]
    
    print('RESPONSE', message['Trigger']['Dimensions'][0]['name'] if isinstance(message, dict) else message)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment