try / catch не выполняется или не обнаруживает ошибку - PullRequest
1 голос
/ 03 августа 2020

Я пытаюсь создать команду справки и вернуть сообщение, если возникает ошибка, то есть, если пользователь закрыл личные сообщения и сообщает им об этом, но это просто не работает. Он продолжает отправку исходных сообщений и не выполняет функцию перехвата, если получает ошибку. Я новичок в 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?')

1 Ответ

2 голосов
/ 03 августа 2020

send возвращает обещание , поэтому вам нужно либо .catch обещание, либо использовать async/await с блоком try/catch.

A обещание - это объект, представляющий асинхронную c операцию, поэтому ошибка, возникающая внутри него, не будет перехвачена блоком 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?')
    }
}
...