I have a questions about how the finally block executes in a node js application running in a lambda as I am observing some werid behavour.
I have an AWS lambda API endpoint written in node/express/typescript that is suppose to save any thrown errors into a DynamoDb table.
The logic to put the error object into DDB inside a finally block as shown by below pseudocode.
async getById(req: Request, res: Response): Promise<void> {
try {
throw error
} catch (error) {
print error
return response to user
} finally {
save error to dynamo DB
}}
Flow is: User -> CloudFront -> Api Gateway -> Lambda -> Application -> getByID method(throws an error) -> Dynamo DB
Below are the observations:
And so on. So the pattern is, current error never shows up in Dynamo DB unless a new invocation of the Api occur.
I have tried below to no avail:
So my questions are:
It sounds like the execution context is being frozen once you return a value and the finally block is not running until the context is unfrozen for the next invocation. Lambda does not implicitly wait for the node event loop to empty before freezing the context. You can explicitly tell Lambda to wait to return until the event loop is empty. However, I would suggest you don't do that. If you want to consistently write the error to your DB you will have to write it before returning a response.
Further reading: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With