[英]How do you catch an error and send it to the bot owner in discord.js v12?
[英]How do you catch an error in this timer code for discord.js?
我正在 javascript 中制作一個 discord 機器人,並且我正在嘗試這樣做,以便當有人輸入無效的時間時,它會告訴您出現錯誤,而不是讓機器人崩潰。
我已經研究了一段時間,但找不到如何阻止它使機器人崩潰的答案,只能用類似“那不是有效數字”之類的方式回復。 有人可以幫助我嗎?
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;
}
});
isNaN 是 JavaScript function 返回 boolean 以確定給定輸入是否為數字。 它代表is Not a Number 。 幾個例子:
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() 的更多信息
根據這個邏輯,我們可以通過檢查第二個參數是否為數字來將其用於您的代碼 => 在本例中為變量“時間”:
if (isNaN(time)) return message.reply('Please enter a number!');
您可以使用
if(isNaN(time)) return message.reply("That is not a valid number.")
isNaN()
為“非數字”值返回true
,這應該正是您所需要的,您可以在此處閱讀更多相關信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.