[英]try/catch doesn't execute or catch an error
我正在尝试发出帮助命令,并在发生错误时返回一条消息,这意味着如果用户已关闭 DM 并通知他们,但它似乎不起作用。 它继续发送原始消息,如果出现错误则不会执行 catch function。 我是 javascript 的新手,所以也许我只是做错了或输入了错误的内容。
try {
message.author.send('Here\'s a list of my commands:')
message.author.send('Commands')
message.channel.send('I sent you a dm with all the commands. If you haven\'t received it, check if your dms are open.')
} catch (error) {
message.channel.send('Couldn\'t send you a message. Are your dms open?')
send
返回 promise ,因此您需要.catch
promise,或者将async/await
与try/catch
块一起使用。
promise是表示异步操作的 object,因此其中发生的错误不会被 try/catch 块捕获。
message.author.send('Here\'s a list of my commands:')
message.author.send('Commands')
message.channel.send('I sent you a dm with all the commands. If you haven\'t received it, check if your dms are open.')
.catch((error) => {
message.channel.send('Couldn\'t send you a message. Are your dms open?')
});
altnernative,如果你使用async/await
是这样的:
async function whatever() {
...
try {
await message.author.send('Here\'s a list of my commands:')
await message.author.send('Commands')
await message.channel.send('I sent you a dm with all the commands. If you haven\'t received it, check if your dms are open.')
} catch (err) {
await message.channel.send('Couldn\'t send you a message. Are your dms open?')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.