首页 > 解决方案 > 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?')

标签: javascriptnode.jsdiscorddiscord.js

解决方案


send 返回一个 promise,因此您需要使用.catchpromise 或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的是这样的:

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

推荐阅读