AWS Lambda函数从API网关返回错误,但直接调用时不会返回错误



我有一个简单的Lambda函数,它将项目写入DynamoDB表。username是分区键,createDateTime是排序键。

从Lambda本身调用此函数成功地将项插入到表中。然而,当通过API网关调用时,我收到以下错误

{
  "errorMessage": "Error putting order into dynamodb: MultipleValidationErrors: There were 14 validation errors:n* InvalidParameterType: Expected params.Item['createDateTime'] to be a structuren* UnexpectedParameter: Unexpected key '0' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '1' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '2' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '3' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '4' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '5' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '6' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '7' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '8' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '9' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '10' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '11' found in params.Item['createDateTime']n* UnexpectedParameter: Unexpected key '12' found in params.Item['createDateTime']"
}

我不明白为什么我的代码在本地调用时工作,而不是通过API网关调用时?下列代码:

var AWS = require("aws-sdk");
var DOC = require("dynamodb-doc");
AWS.config.update({region: "eu-west-1"});
var dynamodb = new DOC.DynamoDB();
exports.handler = function(event, context) {
    console.log('Received event:', JSON.stringify(event, null, 2));
    var tableName = "MarketOrder";
    if (event.http_method == 'POST') {
        var datetime = new Date().getTime().toString();
        dynamodb.putItem({
            "TableName": tableName,
            "Item" : { 
                "username"   : event.username,
                "createDateTime" : datetime,
                "orderType": event.orderType,
                "numberOfShares": event.numberOfShares,
                "price": event.price,
                "validToDate": event.validToDate
            }
        }, function(err, data) {
            if (err) {
                console.log("dynamodb error: " + err);
                context.done('Error putting order into dynamodb: ' +err);
            }
            else {
                console.log('great success: '+JSON.stringify(data, null, '  '));
                context.succeed('Sucessfully saved market order');
            }
        });
    } 
    ....
    } else {
        context.fail('Invalid operation specified:' + event.http_method);
    }
};

很可能您的映射模板有问题。我建议为你的API打开CloudWatch日志以进行故障排除。

见https://rpgreen.wordpress.com/2016/08/30/easy-api-gatewaylambda-serverless-api-loggingdebugging/

我有过类似的经历,并了解到以下内容:当独立测试Lambda函数时(使用AWS Lambda控制台的内置'Test'功能),Event参数是一个对象;当使用内置API网关测试功能时,Event是一个字符串。我通过比较两种不同场景的CloudWatch日志了解到这一点,并注意到,虽然两种情况下的输入看起来很相似,但用于生成格式良好的JSON的所有换行字符都会在Event字符串中产生'n'字符,这是我的Lambda函数(用Node.js编写,使用JSON.parse())无法解释的。所以我添加了以下代码来防弹我的函数,它似乎工作得很好(注意这里我的代码正在检查事件内部的'body'对象,但如果需要,可以在整个事件对象上使用):

  var body;
  switch(typeof(event.body)) {
    case "string":
      //strips all-types of linebreak and carriage return characters from the event.body string
      var str = event.body.replace(/[rn]+/gm,"");
      body = JSON.parse(str);
      break;
    case "object":
      body = event.body;
      break;
    default:
      throw("invalid input for event.body");
  }

相关内容

  • 没有找到相关文章

最新更新