2
votes

Every time I have a syntax error or I just want to send a custom error in my AWS Lambda function, I get the same 502 Bad Gateway response (Internal server error).

I tried that simple code:

module.exports.saveImage = (event, context, callback) => {
    callback("the sky is falling!"); // also tried sending new Error("the sky is falling!")
}

And still getting the same "Internal server error" response instead of the defined one.

This is my function in the serverless.yml file:

saveImage:
  handler: handler.saveImage
  environment:
    BUCKET: ${self:custom.bucket}
  events:
  - http:
      path: saveImage
      method: post
      cors: true,
      integration: lambda-proxy

May I have misunderstood something from this article? It seems to recieve the "errorMessage": "the sky is falling!" in the API Gateway response (and that's what I would expect).

https://aws.amazon.com/es/blogs/compute/error-handling-patterns-in-amazon-api-gateway-and-aws-lambda/

1
Did you configure the API Gateway's Integration Response section to handle the Lambda's response?Popoi Menenet
I've updated my question with the serverless.yml config. By the way, I can receive the response if I put the error in the second argument, like this: callback(null, { body: JSON.stringify( { errorMessage: "my error" }) }); Is that how we should handle errors? I thought we can use the first argument to send errors.Emi

1 Answers

3
votes

If you use integration: lambda-proxy, you need to return a proper error response from your Lambda, not from API Gateway.

In this case, you can use what already tried:

callback(null, { body: JSON.stringify( { errorMessage: "my error" })

I thought we can use the first argument to send errors

You can, if you use integration: lambda in your serverless.yml but in your case, you're not.