【问题标题】:How to inform the user on POST fails in Dialogflow's promises?如何在 Dialogflow 承诺中通知用户 POST 失败?
【发布时间】:2019-09-27 01:11:28
【问题描述】:

在我的对话流代理中,作为实现,我在代码中有一部分调用了一个 Promise,并且机器人使用来自服务器的一些数据来响应用户。如果成功,一切都会按预期进行。但是,如果出现错误(例如,切断),我想向用户打印一条消息,说明发生了错误,他/她不需要等待永恒的答案。

      return new Promise( (resolve,reject) => {
        const request = require('request-promise-native');
        const options = {  
          uri: 'https://server.server.com/example',
          method: 'POST',
          headers: {
            'api-token': 'code'
        },
          body: {
            user:'user_name'
         },
        json: true
    };

    request(options)
        .then(function (body) {
            // POST succeeded
            console.log("got: "+ body);
            agent.add("SUCCESS");
            resolve();
        })
        .catch(function (err) {
            // POST failed...
            console.log("ERROR!: " + err);            
            agent.add("I am sorry for the inconvenience but an error happened during your last call.");
            agent.add("Please try in a while");
            console.log(err.stack);
        });
    });

失败的 POST 消息后的错误消息打印在日志文件中(因此它进入 .catch 部分)但用户没有收到任何消息,agent.add() 函数在其中不起作用案件,这似乎很奇怪。当 promise 过程失败时,如何向用户打印消息?

【问题讨论】:

    标签: node.js dialogflow-es


    【解决方案1】:

    使用 try-catch 语句?我不知道发生了什么错误,但如果你收到错误,你肯定能抓住它吗?

    【讨论】:

    • 感谢您的回复。在我的情况下,服务器已关闭,并且 request(options).catch 正在捕获错误(它在日志中打印有关错误,“POST failed”注释下方的一行),但下面的 agent.add() 函数没有似乎没有任何反应。日志的最后一行再次正常工作。
    • “agent.add()”在做什么?
    • 它打印聊天机器人的响应。 agent.add("你好!");打印“你好!”。 console.log() 打印在日志中。
    【解决方案2】:

    你可以尝试这样做,根据发布请求的响应。例如,构建一个 promise 函数,并在发生错误时拒绝错误。然后在您的意图处理程序中,如果有来自函数的拒绝响应,则获得拒绝的答案并显示您的错误消息。

    我不熟悉“request-promise-native”,但你可以在你的 promise 中使用“request”模块试试这个

    request.post(options, (error, response, body) => {
       if (error) {
         console.log(error);
         reject(error);
       }
       else {
         answer = body;
         resolve(answer);
       }
    });
    

    然后在您的意图处理程序中

    promisefunction()
    .then((resolve, reject) => {
    if (reject)
    {
     agent.add("I am sorry for the inconvenience but an error happened during your last call.");
     agent.add("Please try in a while");
    }
    else
    agent.add("SUCCESS");
    }
    
    

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 2014-02-23
      • 2019-02-15
      • 1970-01-01
      相关资源
      最近更新 更多