Handling errors in AWS Lambda function with API Gateway

 ̄綄美尐妖づ 提交于 2021-01-28 02:51:49

问题


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:


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.



来源:https://stackoverflow.com/questions/45557042/handling-errors-in-aws-lambda-function-with-api-gateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!