0

I'm trying to return errors from my lambda functions but for all of the errors it just returns status 502 with message Internal server error. Previously it was just returning cors error for all types of returned errors. After adding 'Access-Control-Allow-Origin' : '*' in api gateway responses, i'm getting 502 error. I've logged thrown errors in catch block & i can see the specific errors in CloudWatch. I've seen this question but that didn't help anyway. Please note that instead of using callback i'm using async await. Also i've tried with & without lambda-proxy integration but the response is same. Do i need to configure something else in case of lambda-proxy?

const test = async (event, context) => {
  try {
    context.callbackWaitsForEmptyEventLoop = false;
    const error = { status: 400, message: 'my custom error' };
    throw error;
  } catch(error) {
    console.log('==== error ====', error);

    return createErrorResponse(error.status || 500, error.errors || error.message);
  }

createErrorResponse

const createErrorResponse = (statusCode, message, stack={}) => ({
  statusCode,
  headers: {
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Credentials': true,
  },
  body: JSON.stringify({
    error: message
  }),
  stack: JSON.stringify({ stack })
});

export default createErrorResponse;

serverless.yml

test:
    handler: api/index.test
    timeout: 360
    events:
      - http:
          path: test-lambda-api
          method: post
          cors: true
Kamran Arshad
  • 81
  • 1
  • 16

1 Answers1

1

When using Lambda proxy integration with API Gateway, the response from Lambda is expected in a certain format:

var response = {
    "statusCode": 200,
    "headers": {
        "my_header": "my_value"
    },
    "body": JSON.stringify(responseBody),
    "isBase64Encoded": false
};

Include your stack JSON key inside the body itself. You can also refer to this post for more info: https://aws.amazon.com/premiumsupport/knowledge-center/malformed-502-api-gateway/

Also, you should enable debug logs for the API Gateway stage which will give a better understanding of what is sent and received from the API GW integration.

Paradigm
  • 1,876
  • 1
  • 12
  • 16