在抛出最终错误之前重试3次

时间:2019-07-18 23:36:35

标签: angular typescript google-cloud-functions twilio

在我的Google云功能中,我正在尝试使用以下代码通过twilio发送短信。我收到错误存在错误=>错误:ESOCKETTIMEDOUT 我想在抛出最终错误之前至少重试以下代码3次。我不知道该怎么做到。

const twilio = require('twilio');
const accountSid = new MyKeys().AccountSID();
const authToken = new MyKeys().AuthToken();
const client = new twilio(accountSid, authToken);

client.messages
  .create(textMessage)
  .then((msg: any) => {
    console.log('message sent successfully => ' + textMessage.body);
  })
  .catch((smsError: any) =>
    console.log('there was an error => ' + smsError)
  );

2 个答案:

答案 0 :(得分:1)

您可以创建一个函数来发送消息并在catch块中递归调用它。


const twilio = require('twilio');
const accountSid = new MyKeys().AccountSID();
const authToken = new MyKeys().AuthToken();
const client = new twilio(accountSid, authToken);

// call send message function, pass how many times to try in arguments
sendMessage(3);

function sendMessage(tryCount) {
  client.messages
    .create(textMessage)
    .then((msg: any) => {
      console.log("message sent successfully => " + textMessage.body);
      return;
    })
    .catch((smsError: any) => {
      // stop condition
      tryCount = tryCount - 1;
      if (tryCount === 0) {
        console.log("there was an error => " + smsError);
        return;
      }
      sendMessage(tryCount);
    });
}


答案 1 :(得分:0)

我不必重试3次。通过查看文本消息,我解决了错误ESOCKETTIMEDOUT的问题。我意识到我没有正确输入“发件人”电话号码,并且它是空的。解决此问题后,错误ESOCKETTIMEDOUT消失了。