【问题标题】:Serverless offline custom error from API gateway with Lambda来自 Lambda 的 API 网关的无服务器离线自定义错误
【发布时间】:2017-06-23 14:32:50
【问题描述】:

有没有办法从 API 网关返回自定义错误对象和状态码?我得到200状态。

 var response = {
    status: 400,
    errors: [
       {
          code:   "226",
          message: "Password and password confirmation do not match."
        }
    ]
 }

context.done(JSON.stringify(response));

【问题讨论】:

    标签: aws-lambda serverless-framework


    【解决方案1】:

    如果你想用错误响应,你必须使用带有错误响应结构的成功回调。

    如果您使用 context.fail() 回调,AWS 将假定 Lambda 在技术上失败并使用您的 API 网关中存在的默认映射进行响应。

    错误响应示例:

    'use strict';
    
    module.exports.hello = (event, context, callback) => {
      const response = {
        statusCode: 400,
        body: JSON.stringify({
          errors:[{
            code: "226",
            message:"Password confirmation do not match"
          }]
        }),
      };
      context.done(null, response);
    };
    

    【讨论】:

    • 对不起,我没有使用 context.fail。我正在使用 context.done 发送错误。我还需要向客户端发送状态代码和有效的消息。就像用户在没有有效密码的情况下尝试登录时一样,我需要发送一条消息。
    • 我将示例更新为完整的 lambda。在您更新的示例中,响应仍然设置错误。
    • 它返回状态码 200。我需要发送带有有效消息的状态码 400。当用户尝试在没有有效密码的情况下登录时,我想发送状态码 400 和有效消息。
    • 看这篇文章你会知道我遇到了什么问题。 [链接] (kennbrodhagen.net/2016/03/09/…)
    • 这篇博文直接使用 AWS API Gateway 和它自己的映射,另一方面,您说您使用的是无服务器框架,它将为您配置网关和映射。我提供的示例是针对无服务器框架配置的。如果您手动进行配置和映射(如博客文章中所述),则需要查找错误。
    【解决方案2】:

    这样我可以更改 API 网关。我可以管理我对使用 s-templates.json 添加此代码库的 API 响应。

    ValidationError":{
      "selectionPattern": ".*ValidationError.*",
      "statusCode": "400",
      "responseParameters": {
        "method.response.header.Access-Control-Allow-Headers": "'Content-
        Type,X-Amz-Date,Authorization,X-Api-Key,Cache-Control,Token'",
        "method.response.header.Access-Control-Allow-Methods": "'*'",
        "method.response.header.Access-Control-Allow-Origin": "'*'"
      },
      "responseModels": {},
      "responseTemplates": {
        "application/json": "$input.path('$.errorMessage')"
      }
    }
    

    这样我会返回带有 400 statusCode 和有效消息的响应。

    module.exports.handler = function(event, context) {
      const validationError={
        statsCode:"ValidationError",
        section:"Login",
        validationType:"emailConfirmation",
        message:"Email is not confirmed",
        otherInfo:"Would you like to get the email again?",
        client:"web|ios|android"
      }
      context.done(null, response);
    };
    

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 2016-12-06
      • 2020-08-05
      • 2019-09-29
      • 1970-01-01
      • 2021-12-01
      • 2019-11-24
      • 1970-01-01
      • 2017-02-26
      相关资源
      最近更新 更多