【问题标题】:How do you catch an error in this timer code for discord.js?您如何在 discord.js 的计时器代码中发现错误?
【发布时间】:2021-01-14 22:20:12
【问题描述】:

我正在用 javascript 制作一个不和谐的机器人,并且我正在努力做到这一点,当有人输入一个无效的时间时,它会告诉你你有一个错误,而不是让机器人崩溃。

我已经研究了一段时间,但无法找到如何阻止它使机器人崩溃的答案,只是回复诸如“这不是一个有效的号码”之类的东西。有人可以帮我吗?

client.on('message', message => {
  let args = message.content.substring(PREFIX.length).split(" ");
  switch (args[0]) {
    case 'timer':
      let time = (args[1]);
      if (!time) {
        return message.reply("You didnt specify a time!");
      }
      message.reply(`Timer started for ${ms(ms(time))}`)
      setTimeout(function() {
        message.reply(`your timer has stopped`)
      }, ms(time));
      break;
  }
});

【问题讨论】:

    标签: javascript timer discord.js bots


    【解决方案1】:

    isNaN()

    isNaN 是一个 JavaScript 函数,它返回一个布尔值以确定给定输入是否为数字。它代表不是数字。 几个例子:

    isNaN(8); // Expected outcome 'false' since 8 is a number
    isNaN('hello!'); // Expected outcome 'true' since 'hello!' is not a number.
    // It also works for numbers inside of a string:
    isNaN('23'); // Expected outcome 'false' since 23 is a number.
    

    你可以阅读更多关于 isNaN() here

    在您的代码中

    根据这个逻辑,我们可以通过检查第二个参数是否为数字来将其用于您的代码 => 在这种情况下,变量“时间”:

    if (isNaN(time)) return message.reply('Please enter a number!');
    

    【讨论】:

      【解决方案2】:

      你可以使用

      if(isNaN(time)) return message.reply("That is not a valid number.")
      

      isNaN() 为“非数字”值返回 true,这应该正是您所需要的,您可以阅读更多关于它的信息 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-30
        • 1970-01-01
        • 2012-07-24
        • 1970-01-01
        相关资源
        最近更新 更多