简体   繁体   English

try/catch 不执行或捕获错误

[英]try/catch doesn't execute or catch an error

I'm trying to make a help command, and return a message if an error occurs, meaning if the user has DMs closed and inform them about it, but it just doesn't seem to work.我正在尝试发出帮助命令,并在发生错误时返回一条消息,这意味着如果用户已关闭 DM 并通知他们,但它似乎不起作用。 It goes on with sending the original messages and doesn't execute the catch function if it gets an error.它继续发送原始消息,如果出现错误则不会执行 catch function。 I'm overall new to javascript, so maybe I've just done it wrong or mistyped something.我是 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 returns a promise , so you'd need to either .catch the promise, or use async/await with a try/catch block. send 返回 promise ,因此您需要.catch promise,或者将async/awaittry/catch块一起使用。

A promise is an object that represents an async operation, so an error that occurs inside it, won't be caught by a try/catch block. 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?')
    });

The altnernative, if you're using async/await is like this: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM