Amazon SQS trigger to invoke a Lambda function

Using an Amazon SQS trigger to invoke a Lambda function

The Lambda function retrieves a batch of SQS messages from the event parameter that it receives. The function logs the content of each message. When an exception occurs for one or more of the received messages, the handler returns SQSBatchResponse that contains batchItemFailure for failed messages that can be used for message reprocessing or move failed messages to DLQ

Select language:

Usage Example with Node:

Consuming an SQS event with Lambda using JavaScript with batch item handling.

exports.handler = async (event, context) => {
    const batchItemFailures = [];
    if (event.Records.length == 0){
        console.log('Empty SQS Event received');
        return { batchItemFailures };
    }
    for(const message of event.Records){
        const result = await processMessageAsync(message);
        if(result !== null){
            batchItemFailures.push(result);
        }
    }
    return { batchItemFailures };
};

async function processMessageAsync(message) {
    try {
            console.log(`Processed message ${message.body}`);
            // TODO: Do interesting work based on the new message
            await Promise.resolve(1); //Placeholder for actual async work
            return null;
        } catch (err) {
            console.error(`An error occurred while processing ${message} - Error: ${err.message}`);
            return { itemIdentifier: message.messageId };
        }
    }
                                                      



Created by:

Mohammed Tomeh

Mohammed Tomeh

Cloud Application Architect at AWS

Follow on LinkedIn