Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在DynamoDB中搜索表失败时如何回调错误消息_Javascript_Amazon Web Services_Aws Lambda_Amazon Dynamodb - Fatal编程技术网

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

Javascript 在DynamoDB中搜索表失败时如何回调错误消息,javascript,amazon-web-services,aws-lambda,amazon-dynamodb,Javascript,Amazon Web Services,Aws Lambda,Amazon Dynamodb,我目前正在使用AWS Lambda JavaScript代码尝试搜索DynamoDB表,然后将其实现到Amazon Alexa应用程序中,但这对我的要求并不重要。以下是我正在努力解决的代码: function readDynamoItem(params2, callback) { var AWS = require('aws-sdk'); AWS.config.update({region: AWSregion}); var 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被卡住的位置,然后检查以到达细节


然后,您可以精确定位异常并将注意力集中在它上。至少对我来说,根本原因很多时候是出乎意料的,因为Lambdas迫使我采用不同的思维方式。

1。我建议用DynamoDB代替。2.你的lambda有可能超时了吗?3.代码的else块应该是callbacknull,data如果您试图返回一个成功的路径是的,我将尝试更改为document client使用什么参数来代替对document client的扫描,或者这是否同样有效??我不认为lambda会超时,因为它在没有错误的情况下工作正常。成功路径后的回调只是为了展示我有自己的代码,我只是不想让问题太长而无法解释文档客户端的工作方式基本相同,它主要消除了调用类型的需要。尝试在回调时添加一个返回。。。调用。我已经尝试使用带有扫描的文档客户端,但它不起作用。即使参数没有返回错误,它也会给我同样的错误。您的意思是只添加returncallbackerror;?这似乎不起作用。你能分享你的全部代码吗?因为您提供的代码片段没有为我提供足够的上下文来进一步帮助。是的,我尝试过这样记录日志,但所发生的一切是,在找不到任何内容后,它会执行一个结束请求,而不是回调输出。以下是日志:TypeError:无法读取未定义的属性“team1”。然后:END RequestId:9f78082f-31dc-11e8-b55a-0df2f95d3cecI我想您在这行中得到了吗?team1=jsonToStringdata.Items[0].team1;这通常是由于没有从查询数据=[]返回任何结果。在访问属性之前,需要检查数据项[0]是否存在。如果您没有得到任何回复,则可能与您的查询或数据库本身有关。抱歉,我本应发布消息说,我通过添加If语句解决了此问题:ifdata.Count==0{callbackerror;}这是因为lambda没有意识到“找不到任何东西”是一个错误,而是以空json返回数据