I have a desktop application that we are developing using Electron Framework. It invokes AWS Lambda functions directly using their alias ARNs. The Lambda functions are being developed in python 3.6. There is no API gateway handling requests as they are just managed by direct invocations to Lambda. The way such requests are processed by Lambda is that as specified by AWS documentation:
When you invoke a Lambda function, Lambda receives the invocation request and validates the permissions in your execution role, verifies that the event document is a valid JSON document, and checks parameter values.
The problem arises when Lambda verifies the event document, because when it is not valid, it automatically sends an error message using its own format. This is explained by AWS documentation as:
If the request passes validation, Lambda sends the request to a function instance. The Lambda runtime environment converts the event document into an object, and passes it to your function handler.
My question is: How can I get control over the event document and parse it myself before the Lambda runtime environment does it for me? I need to specify my own formatted error message in case of receiving an invalid JSON event. Also, I don't need to get the python stack-trace at the electron JavaScript app. Here is an example of the error message in case parsing the event document fails. The invalid JSON event in this instance was having an extra comma:
{"errorMessage": "Expecting property name enclosed in double quotes: line 3 column 1 (char 54)", "errorType": "JSONDecodeError", "stackTrace": [["/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", 355, "raw_decode", "obj, end = self.scan_once(s, idx)"]]}
I tried to overcome this problem using python decorators that can introduce sort of a middle-ware before the lambda invocation takes place, but nothing seemed to work. The decorators that I tried were the ones developed by aws-powertools, lambda-decorators, and aws-lambda-decorators. I think there is also a middleware engine that can help with this: middy, but it can be only used for Node.js Lambda functions. I even seriously put the whole Lambda python file in a try-except statement, but it didn't seem to work, either. I searched some other solutions, but most of them tackle the issue at the API Gateway such as in Chalice Framework, but not in the Lambda itself.
I would be pleased if you can suggest a solution that can work as a middle-ware that gets the event document before the Lambda runtime environment parses it into an object.
Thanks in advance..