简体   繁体   中英

AWS Lambda, API Gateway returns Malformed Lambda proxy response, 502 error

After a lot of googling and a few hours of trial and error I can't find out why i'm getting this error message:

Execution failed due to configuration error: Malformed Lambda proxy response

When I run the lambda using the test lambda functionality it works fine. Answers to similar questions to this state that the response from the lambda needs to meet this format:

{
  "isBase64Encoded": true|false,
  "statusCode": httpStatusCode,
  "headers": { "headerName": "headerValue", ... },
  "body": "..."
}

Below is the lambda I'm using (which adheres to this format):

'use strict';

var aws = require('aws-sdk');
var ses = new aws.SES();

var RECEIVER = "XXXX@XXXX.com";
var SENDER = "XXXX@XXXX.com";

const response_success = {
      'isBase64Encoded': false,
      'statusCode': 200,
      'headers': {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: 'ok'
      }),
};

const response_error = {
    'isBase64Encoded': false,
    'statusCode': 400,
    'headers': {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        message: 'error'
    }),
};

exports.handler = (event, context, callback) => {
    sendEmail(event, function(error, data) {
        if (error) {
           callback(response_error);
        } else {
           callback(null, response_success);
        }
    });
};

function sendEmail(event, done) {
    var params = {
        Destination: {
            ToAddresses: [
                RECEIVER
            ]
        },
        Message: {
            Body: {
                Text: {
                    Data: event.message,
                    Charset: 'UTF-8'
                }
            },
            Subject: {
                Data: 'Lamda Test Email',
                Charset: 'UTF-8'
            }
        },
        Source: SENDER
    }
    ses.sendEmail(params, done);
}

I don't think its a configuration issue and i'm using Terraform to build the infrastructure if thats' any help. Thanks in advance!

EDIT: (Added the error logs below)

Execution log for request test-request
Fri May 05 16:36:22 UTC 2017 : Starting execution for request: test-invoke-request
Fri May 05 16:36:22 UTC 2017 : HTTP Method: POST, Resource Path: /messages
Fri May 05 16:36:22 UTC 2017 : Method request path: {}
Fri May 05 16:36:22 UTC 2017 : Method request query string: {}
Fri May 05 16:36:22 UTC 2017 : Method request headers: {}
Fri May 05 16:36:22 UTC 2017 : Method request body before transformations: { "message" : "test" }
Fri May 05 16:36:22 UTC 2017 : Endpoint request URI: https://lambda.eu-west-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-west-1:670603659598:function:mailer_lambda/invocations
Fri May 05 16:36:22 UTC 2017 : Endpoint request headers: {x-amzn-lambda-integration-tag=test-request, Authorization=****************************************************************************************************************************************************************************************************************************************************************************************************************************************cd4bef, X-Amz-Date=20170505T163622Z, x-amzn-apigateway-api-id=jnnd4wh3f8, X-Amz-Source-Arn=arn:aws:execute-api:eu-west-1:670603659598:jnnd4wh3f8/null/POST/messages, Accept=application/json, User-Agent=AmazonAPIGateway_jnnd4wh3f8, X-Amz-Security-Token=FQoDYXdzEPH//////////wEaDB1y8s+RanRAP61EAyK3A1f/o2BrYfqUOQwsrn7bRF6OMmeD3Se+WVWA1reC3tZZ6+IfnFa0LVNnaaNM27o/Vqc/m4tnQR5xUACK3I6ssbkwHj9E4sM3sQ4L+zNQSnkZhMAIRxbyxHJRp1E9/8XnVxRJAWF5ynWCmDxe2tQQ8SXCnQKIKzJypIgp0E0BD3hZ92soW6wID64uaufk+qYXiV7AJxd+Z9Gg1TyiwacUA2i0g4xsjDqeAA5wFbI9KoiYK6/+uwpQ5mxdxg6JIxS7H9jULRRn7V9E4YVXsXCWXh8RXqGmigGzWXChYAD3S7b9rBLUpTga3t3SlnnK [TRUNCATED]
Fri May 05 16:36:22 UTC 2017 : Endpoint request body after transformations: {"resource":"/messages","path":"/messages","httpMethod":"POST","headers":null,"queryStringParameters":null,"pathParameters":null,"stageVariables":null,"requestContext":{"accountId":"670603659598","resourceId":"90rzx3","stage":"test-invoke-stage","requestId":"test-invoke-request","identity":{"cognitoIdentityPoolId":null,"accountId":"670603659598","cognitoIdentityId":null,"caller":"670603659598","apiKey":"test-invoke-api-key","sourceIp":"test-invoke-source-ip","accessKey":"ASIAJA3SYDRPGE36PMXQ","cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":"arn:aws:iam::670603659598:root","userAgent":"Apache-HttpClient/4.5.x (Java/1.8.0_112)","user":"670603659598"},"resourcePath":"/messages","httpMethod":"POST","apiId":"jnnd4wh3f8"},"body":"{ \"message\" : \"test\" }","isBase64Encoded":false}
Fri May 05 16:36:22 UTC 2017 : Endpoint response body before transformations: {"errorMessage":"[object Object]"}
Fri May 05 16:36:22 UTC 2017 : Endpoint response headers: {x-amzn-Remapped-Content-Length=0, x-amzn-RequestId=f91382de-31b0-11e7-bfaa-c7e2e3193355, Connection=keep-alive, Content-Length=34, X-Amz-Function-Error=Handled, Date=Fri, 05 May 2017 16:36:22 GMT, X-Amzn-Trace-Id=root=1-590caa06-47c0526e9aba46d52e47aee5;sampled=0, Content-Type=application/json}
Fri May 05 16:36:22 UTC 2017 : Execution failed due to configuration error: Malformed Lambda proxy response
Fri May 05 16:36:22 UTC 2017 : Method completed with status: 502

Thanks for the help @johni and @UXDart. The issue was that the integration request between api gateway and lambda was transforming the request body ( You can find out more about this here )

So I changed the handler to parse event.body so I can now access the correct data from the event. (NB Testing this in lambda will cause the function to time out so you will need to test from api-gateway)

Here is what I changed:

exports.handler = (event, context, callback) => {
    const body = JSON.parse(event.body);

    sendEmail(body, function(error, data) {
        if (error) {
           callback(null, response_error);
        } else {
           callback(null, response_success);
        }
    });
};

not completely sure, but you should just return a result, even if is an error, because you are using the statuscode

so change the callback(response_error); to callback(null, response_error);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM