如何在 DynamoDB 中搜索表失败时回调错误消息



我目前正在使用 AWS Lambda JavaScript 代码来尝试搜索 DynamoDB 表,然后将其实施到 Amazon Alexa 应用程序中,但这对我所问的内容并不重要。这是我正在努力的代码:

function readDynamoItem(params2, callback) {
        var AWS = require('aws-sdk');
        AWS.config.update({region: AWSregion});
        var dynamodb = new AWS.DynamoDB();
        console.log('reading item from DynamoDB table');
        dynamodb.scan(params2, function (err, data){
            if (err) {
                callback("error");
                //console.log(err, err.stack); // an error occurred
            }
            else{
               callback(data);
            }
        });
    }

因此,当发生错误时,我希望它回调消息"error",然后在此处使用它:

const params2 = {
            TableName: 'Fixtures',
            FilterExpression: 'team1 = :value',
            ExpressionAttributeValues: {':value': {"S": MyQuestion.toLowerCase()}}
};
readDynamoItem(params2, myResult=>{
            say = myResult;
            this.response.speak(say).listen('try again');
            this.emit(':responseReady');
});

我现在得到的只是测试时的这个响应,我认为由于错误只是结束程序而不是回调错误以在实现中使用:

Response:
{
  "errorMessage": "RequestId: 0f586880-2ddb-11e8-bdf7-07b4c224b25d Process exited before completing request"
}

任何帮助将不胜感激。

以下是我项目的完整代码,以供进一步参考:

const AWSregion = 'eu-west-1';  
const Alexa = require('alexa-sdk');
const AWS = require('aws-sdk');
AWS.config.update({
    region: AWSregion
});
exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    // alexa.appId = 'amzn1.echo-sdk-ams.app.1234';
    // alexa.dynamoDBTableName = 'YourTableName'; // creates new table for session.attributes
    alexa.registerHandlers(handlers);
    alexa.execute();
};
const handlers = {
    'LaunchRequest': function () {
        this.response.speak('welcome to magic answers.  ask me a yes or no question.').listen('try again');
        this.emit(':responseReady');
    },

    'MyIntent': function () {
        var MyQuestion = this.event.request.intent.slots.MyQuestion.value;
        console.log('MyQuestion : ' + MyQuestion);

        const params2 = {
            TableName: 'Fixtures',
            FilterExpression: 'team1 = :value',
            ExpressionAttributeValues: {':value': {"S": MyQuestion.toLowerCase()}}
        };
        const params3 = {
            TableName: 'Fixtures',
            FilterExpression: 'team2 = :value',
            ExpressionAttributeValues: {':value': {"S": MyQuestion.toLowerCase()}}
        };
        readDynamoItem(params2, myResult=>{
            var say = MyQuestion;
            //if nothing is found when scanning for team1, scan team2
            if (myResult == "error"){
                readDynamoItem(params3, myResult2=>{
                    say = myResult2;
                    say = 'The top scorer for ' + MyQuestion + ' is ' + myResult2;
                    this.response.speak(say).listen('try again');
                    this.emit(':responseReady');
                });
            } 
            else{
                say = myResult;
                say = 'The top scorer for ' + MyQuestion + ' is ' + myResult;
                this.response.speak(say).listen('try again');
                this.emit(':responseReady');
            }
        });
    },
    'AMAZON.HelpIntent': function () {
        this.response.speak('ask me a yes or no question.').listen('try again');
        this.emit(':responseReady');
    },
    'AMAZON.CancelIntent': function () {
        this.response.speak('Goodbye!');
        this.emit(':responseReady');
    },
    'AMAZON.StopIntent': function () {
        this.response.speak('Goodbye!');
        this.emit(':responseReady');
    }
};
//  END of Intent Handlers {} ========================================================================================
//  Helper Function  =================================================================================================
//reading the Fixtures table
function readDynamoItem(params2, callback) {
    var AWS = require('aws-sdk');
    AWS.config.update({region: AWSregion});
    var dynamodb = new AWS.DynamoDB();
    var team1;
    var team2;

    console.log('reading item from DynamoDB table');
    dynamodb.scan(params2, function (err, data){
        if (err) {
            callback("error");
            //callback("error");
            //console.log(err, err.stack); // an error occurred
        }
        else{
            console.log(data); // successful response
            team1 = jsonToString(data.Items[0].team1);
            team2 = jsonToString(data.Items[0].team2);
            var t1goals = jsonToString(data.Items[0].t1goals);
            var t2goals = jsonToString(data.Items[0].t2goals);
            t1goals = parseInt(t1goals);
            t2goals = parseInt(t2goals);
            var search;
            var chosenValue = Math.random() < 0.5 ? team1 : team2;
            // if goals are equal in a match then it is random which team will score next 
            if(t1goals == t2goals){
                search = chosenValue;
            }
            //if a team has 1 goal more than the other then it is a 3rd more likely they will score next
            else if(t1goals > t2goals && t1goals == 1){
                if(randomInt(1, 3) == 1){
                    search = team2;
                }
                else{
                    search = team1;
                }
            }
            else if(t2goals > t1goals && t2goals == 1){
                if(randomInt(1, 3) == 1){
                    search = team1;
                }
                else{
                    search = team2;
                }
            }
            //if a team has more than 1 goal more than the other then it is a 5th more likely they will score next
            else if(t1goals > t2goals && t1goals > 1){
                if(randomInt(1, 5) == 1){
                    search = team2;
                }
                else{
                    search = team1;
                }
            }
            else if(t2goals > t1goals && t2goals > 1){
                if(randomInt(1, 5) == 1){
                    search = team1;
                }
                else{
                    search = team2;
                }
            }
            var params = {
                TableName: 'yesno',
                FilterExpression: 'team = :value',
                ExpressionAttributeValues: {':value': {"S": search}}
            };
            readDynamoFixtures(params, myResult=>{
                callback(myResult);
            });
        }
    });
}
//read player details from the the yesno table
function readDynamoFixtures(params, callback) {
    var goals =  new Array();
    var playing =  new Array();
    var messages =  new Array();
    var most = 0;
    var mostMessage;
    var dynamodb = new AWS.DynamoDB();
    dynamodb.scan(params, function (err, data) {
                    if (err) console.log(err, err.stack); // an error occurred
                    else{
                        for(var i = 0; i <= (data.Count - 1); i++){
                            console.log(data); // successful response
                            var temp = jsonToString(data.Items[i].playername);
                            messages[i] = temp;
                            temp = jsonToString(data.Items[i].goals);
                            temp = parseInt(temp);
                            goals[i] = temp; 
                            temp = jsonToString(data.Items[i].playing);
                            playing[i] = temp;
                            //compare each players goals
                            if (goals[i] > most && playing[i] == "true"){
                                most = goals[i];
                                mostMessage = messages[i];
                            }
                        }
                    }    
                    callback(mostMessage);
                });
}
//convert database items from json format to string
function jsonToString(str){
    str = JSON.stringify(str);
    str = str.replace('{"S":"', '');
    str = str.replace('"}', '');
    return str;
}
//get a random int between min and max 
function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

编辑:我尝试使用 .query 而不是 .scan 测试此代码,并且错误回调工作正常,这很奇怪,但显然对于此实现,我需要使用 .scan

当您从 Lambda 获得"进程已退出"响应时,大量登录以查看 Lambda 卡住的位置很有帮助,然后检查 Cloudwatch 日志以获取详细信息。

然后,您可以查明异常并专注于它。至少对我来说,根本原因很多时候是出乎意料的,因为 Lambda 迫使人们采用不同的思维方式。

最新更新