try/catch 不执行或捕获错误



我正在尝试制作一个帮助命令,并在发生错误时返回一条消息,这意味着如果用户关闭了DM并通知他们,但似乎不起作用。它继续发送原始消息,如果出现错误,则不执行catch函数。我对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/awaittry/catch块一起使用。

promise是一个表示异步操作的对象,因此它内部发生的错误不会被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?')
});

如果你使用async/await,那么altnernative是这样的:

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?')
}
}

最新更新