首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >有没有办法更改Amazon API Gateway返回的http状态代码?

有没有办法更改Amazon API Gateway返回的http状态代码?
EN

Stack Overflow用户
提问于 2015-07-10 06:38:38
回答 5查看 84.4K关注 0票数 106

例如,如果我想为无效参数返回一个特定的400错误,或者当lambda函数调用导致创建时返回一个201。

我希望有不同的http状态代码,但是看起来api网关总是返回200状态代码,即使lambda函数返回错误。

EN

回答 5

Stack Overflow用户

发布于 2017-01-31 11:00:35

最简单的方法是使用use LAMBDA_PROXY integration。使用这种方法,您不需要在API Gateway管道中设置任何特殊的转换。

返回的对象必须类似于下面的代码片段:

代码语言:javascript
复制
module.exports.lambdaHandler = (event, context, done) => {
    // ...
    let response = {
        statusCode: 200, // or any other HTTP code
        headers: {       // optional
             "any-http-header" : "my custom header value"
        },
        body: JSON.stringify(payload) // data returned by the API Gateway endpoint
    };
    done(null, response); // always return as a success
};

它确实有一些缺点:因为必须特别注意错误处理,并将lambda函数耦合到API Gateway端点;也就是说,如果您不打算在其他任何地方使用它,那么它不是什么大问题。

票数 7
EN

Stack Overflow用户

发布于 2016-11-16 01:16:18

如果使用API Gateway,这是在AWS Compute博客上推荐的方式。检查集成是否与直接Lambda调用一起工作。

代码语言:javascript
复制
var myErrorObj = {
    errorType : "InternalServerError",
    httpStatus : 500,
    requestId : context.awsRequestId,
    message : "An unknown error has occurred. Please try again."
}
callback(JSON.stringify(myErrorObj));

对于直接Lambda调用,这似乎是客户端解析的最佳解决方案。

票数 2
EN

Stack Overflow用户

发布于 2016-10-21 20:07:42

我使用的是无服务器0.5。这就是它的工作原理,对于我的情况

s-function.json:

代码语言:javascript
复制
{
  "name": "temp-err-test",
  "description": "Deployed",
  "runtime": "nodejs4.3",
  "handler": "path/to/handler.handler",
  "timeout": 6,
  "memorySize": 1024,
  "endpoints": [
    {
      "path": "test-error-handling",
      "method": "GET",
      "type": "AWS_PROXY",
      "responses": {
        "default": {
          "statusCode": "200"
        }
      }
    }
  ]
}

handler.js:

代码语言:javascript
复制
'use strict';
function serveRequest(event, context, cb) {
  let response = {
    statusCode: '400',
    body: JSON.stringify({ event, context }),
    headers: {
      'Content-Type': 'application/json',
    }
  };
  cb(null, response);
}
module.exports.handler = serveRequest;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31329495

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档