使用API​​ Gateway处理AWS Lambda函数中的错误 [英] Handling errors in AWS Lambda function with API Gateway

查看:118
本文介绍了使用API​​ Gateway处理AWS Lambda函数中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我遇到语法错误,或者我只想在AWS Lambda函数中发送自定义错误时,都会收到相同的502 Bad Gateway响应(内部服务器错误).

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).

我尝试了简单的代码:

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.

这是我在serverless.yml文件中的功能:

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

我是否可能误解了这篇文章中的某些内容?似乎收到了"errorMessage":天塌了!"在API网关响应中(这就是我所期望的).

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).

推荐答案

如果使用 integration:lambda-proxy ,则需要从Lambda(而不是API Gateway)返回正确的错误响应.

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

如果您在 serverless.yml 中使用 integration:lambda ,则可以,但在您的情况下则不是.

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

这篇关于使用API​​ Gateway处理AWS Lambda函数中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆