[{"data":1,"prerenderedAt":93},["ShallowReactive",2],{"snippet-lambda-function-sqs-report-batch-item-failures":3},{"id":4,"title":5,"contributors":6,"description":10,"extension":11,"gitHub":12,"introBox":15,"languages":19,"meta":25,"resources":26,"services":31,"snippets":34,"stem":87,"tags":88,"type":91,"__hash__":92},"snippets\u002Fsnippets\u002Flambda-function-sqs-report-batch-item-failures.json","Amazon SQS partial batch response Lambda function",[7,8,9],"content\u002Fcontributors\u002Fvictor-feinman.json","content\u002Fcontributors\u002Fcharles-ede.json","content\u002Fcontributors\u002Fsangeetha-kamatkar.json","This snippet demonstrates how to handle an SQS event and implement a partial batch response in a lambda function.","json",{"template":13},{"repoURL":14},"https:\u002F\u002Fgithub.com\u002Faws-samples\u002Fserverless-snippets\u002Ftree\u002Fmain\u002Flambda-function-sqs-report-batch-item-failures",{"headline":16,"text":17},"How it works",[18],"The Lambda function retrieves a source SQS event which may contain messages that cannot be processed. As exceptions are caught processing messages, a list of itemIdentifiers is collected. The collection is returned as batchItemFailures, a JSON serialized list of itemIdentifiers. This sample assumes ReportBatchItemFailures is activated on your lambda function.",[20,21,22,23,24],"Java","Python",".NET","Rust","PHP",{},{"bullets":27},[28],{"text":29,"link":30},"Using Lambda with Amazon SQS","https:\u002F\u002Fdocs.aws.amazon.com\u002Flambda\u002Flatest\u002Fdg\u002Fwith-sqs.html",[32,33],"lambda-event-functions","sqs",[35],{"title":36,"codeTabs":37},"Runtimes",[38,45,52,59,66,73,81],{"id":20,"title":39,"description":40,"snippets":41},"Usage Example with Java:","Implementing partial SQS batch responses using Java.",[42],{"language":43,"code":44},"java","import com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\nimport com.amazonaws.services.lambda.runtime.events.SQSEvent;\nimport com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;\n \nimport java.util.ArrayList;\nimport java.util.List;\n \npublic class ProcessSQSMessageBatch implements RequestHandler&#60;SQSEvent, SQSBatchResponse&#62; {\n    @Override\n    public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) {\n \n         List&#60;SQSBatchResponse.BatchItemFailure&#62; batchItemFailures = new ArrayList&#60;SQSBatchResponse.BatchItemFailure&#62;();\n         String messageId = \"\";\n         for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) {\n             try {\n                 \u002F\u002Fprocess your message\n                 messageId = message.getMessageId();\n             } catch (Exception e) {\n                 \u002F\u002FAdd failed message identifier to the batchItemFailures list\n                 batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(messageId));\n             }\n         }\n         return new SQSBatchResponse(batchItemFailures);\n     }\n}",{"id":21,"title":46,"description":47,"snippets":48},"Usage Example with Python:","Implementing partial SQS batch responses using Python.",[49],{"language":50,"code":51},"py","import json\ndef lambda_handler(event, context):\n    if event:\n        batch_item_failures = []\n        sqs_batch_response = {}\n     \n        for record in event[\"Records\"]:\n            try:\n                # process message\n            except Exception as e:\n                batch_item_failures.append({\"itemIdentifier\": record['messageId']})\n        \n        sqs_batch_response[\"batchItemFailures\"] = batch_item_failures\n        return sqs_batch_response",{"id":22,"title":53,"description":54,"snippets":55},"Usage Example with C#:","Implementing partial SQS batch responses using C#.",[56],{"language":57,"code":58},"dotnet","using Amazon.Lambda.Core;\nusing Amazon.Lambda.SQSEvents;\n\n\u002F\u002F Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.\n[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]\nnamespace sqsSample;\n\npublic class Function\n{\n    public async Task&#60;SQSBatchResponse&#62; FunctionHandler(SQSEvent evnt, ILambdaContext context)\n    {\n        List&#60;SQSBatchResponse.BatchItemFailure&#62; batchItemFailures = new List&#60;SQSBatchResponse.BatchItemFailure&#62;();\n        foreach(var message in evnt.Records)\n        {\n            try\n            {\n                \u002F\u002Fprocess your message\n                await ProcessMessageAsync(message, context);\n            }\n            catch (System.Exception)\n            {\n                \u002F\u002FAdd failed message identifier to the batchItemFailures list\n                batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); \n            }\n        }\n        return new SQSBatchResponse(batchItemFailures);\n    }\n\n    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)\n    {\n        if (String.IsNullOrEmpty(message.Body))\n        {\n            throw new Exception(\"No Body in SQS Message.\");\n        }\n        context.Logger.LogInformation($\"Processed message {message.Body}\");\n        \u002F\u002F TODO: Do interesting work based on the new message\n        await Task.CompletedTask;\n    }\n}",{"id":23,"title":60,"description":61,"snippets":62},"Usage Example with Rust:","Implementing partial SQS batch responses using Rust.",[63],{"language":64,"code":65},"rust","use aws_lambda_events::{\n    event::sqs::{SqsBatchResponse, SqsEvent},\n    sqs::{BatchItemFailure, SqsMessage},\n};\nuse lambda_runtime::{run, service_fn, Error, LambdaEvent};\n\nasync fn process_record(_: &SqsMessage) -&#62; Result&#60;(), Error&#62; {\n    Err(Error::from(\"Error processing message\"))\n}\n\nasync fn function_handler(event: LambdaEvent&#60;SqsEvent&#62;) -&#62; Result&#60;SqsBatchResponse, Error&#62; {\n    let mut batch_item_failures = Vec::new();\n    for record in event.payload.records {\n        match process_record(&record).await {\n            Ok(_) =&#62; (),\n            Err(_) =&#62; batch_item_failures.push(BatchItemFailure {\n                item_identifier: record.message_id.unwrap(),\n            }),\n        }\n    }\n\n    Ok(SqsBatchResponse {\n        batch_item_failures,\n    })\n}\n\n#[tokio::main]\nasync fn main() -&#62; Result&#60;(), Error&#62; {\n    run(service_fn(function_handler)).await\n}\n",{"id":67,"title":68,"description":69,"snippets":70},"Go","Usage Example with Go:","Implementing partial SQS batch responses using Go.",[71],{"language":67,"code":72},"package main\n\nimport (\n\t\"context\"\n\t\"encoding\u002Fjson\"\n\t\"fmt\"\n\t\"github.com\u002Faws\u002Faws-lambda-go\u002Fevents\"\n\t\"github.com\u002Faws\u002Faws-lambda-go\u002Flambda\"\n)\n\nfunc handler(ctx context.Context, sqsEvent events.SQSEvent) (map[string]interface{}, error) {\n\tbatchItemFailures := []map[string]interface{}{}\n\n\tfor _, message := range sqsEvent.Records {\n\t\t\n\t\tif \u002F* Your message processing condition here *\u002F {\t\t\t\n\t\t\tbatchItemFailures = append(batchItemFailures, map[string]interface{}{\"itemIdentifier\": message.MessageId})\n\t\t}\n\t}\n\n\tsqsBatchResponse := map[string]interface{}{\n\t\t\"batchItemFailures\": batchItemFailures,\n\t}\n\treturn sqsBatchResponse, nil\n}\n\nfunc main() {\n\tlambda.Start(handler)\n}\n",{"id":74,"title":75,"description":76,"snippets":77},"JavaScript","Usage Example with JavaScript:","Implementing partial SQS batch responses using JavaScript.",[78],{"language":79,"code":80},"js","export const handler = async (event, context) =&#62; {\n    const batchItemFailures = [];\n\n    for (const record of event.Records) {\n        try {\n            await processMessageAsync(record, context);\n        } catch (error) {\n            batchItemFailures.push({ itemIdentifier: record.messageId });\n        }\n    }\n\n    return { batchItemFailures };\n};\n\nasync function processMessageAsync(record, context) {\n    if (record.body && record.body.includes(\"error\")) {\n        throw new Error(\"There is an error in the SQS Message.\");\n    }\n    console.log(`Processed message: ${record.body}`);\n}\n",{"id":24,"title":82,"description":83,"snippets":84},"Usage Example with PHP:","Implementing partial SQS batch responses using PHP.",[85],{"language":24,"code":86},"&#60;?php\n\nuse Bref\\Context\\Context;\nuse Bref\\Event\\Sqs\\SqsEvent;\nuse Bref\\Event\\Handler as StdHandler;\nuse Bref\\Logger\\StderrLogger;\n\nrequire __DIR__ . '\u002Fvendor\u002Fautoload.php';\n\nclass Handler implements StdHandler\n{\n    private StderrLogger $logger;\n    public function __construct(StderrLogger $logger)\n    {\n        $this-&#62;logger = $logger;\n    }\n\n    \u002F**\n     * @throws JsonException\n     * @throws \\Bref\\Event\\InvalidLambdaEvent\n     *\u002F\n    public function handle(mixed $event, Context $context): array\n    {\n        $sqsEvent = new SqsEvent($event);\n        $this-&#62;logger-&#62;info(\"Processing SQS records\");\n        $records = $sqsEvent-&#62;getRecords();\n\n        $failedRecords = [];\n        foreach ($records as $record) {\n            try {\n                \u002F\u002F Assuming the SQS message is in JSON format\n                $message = json_decode($record-&#62;getBody(), true);\n                $this-&#62;logger-&#62;info(json_encode($message));\n                \u002F\u002F TODO: Implement your custom processing logic here\n            } catch (Exception $e) {\n                $this-&#62;logger-&#62;error($e-&#62;getMessage());\n                \u002F\u002F failed processing the record\n                $failedRecords[] = $record-&#62;getMessageId();\n            }\n        }\n        $totalRecords = count($records);\n        $this-&#62;logger-&#62;info(\"Successfully processed $totalRecords SQS records\");\n\n        \u002F\u002F Format failures for the response\n        $failures = array_map(\n            fn(string $messageId) =&#62; ['itemIdentifier' =&#62; $messageId],\n            $failedRecords\n        );\n\n        return [\n            'batchItemFailures' =&#62; $failures\n        ];\n    }\n}\n\n$logger = new StderrLogger();\nreturn new Handler($logger);\n\n?&#62;","snippets\u002Flambda-function-sqs-report-batch-item-failures",[89,90],"Amazon SQS","Handling Errors","Integration","N_WP4r9K9zgu8kF0LwguWgWsNAXccQCqEUyDo8CqEt0",1792578864447]