javascript - 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/await
与try/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?')
}
}
推荐阅读
- javascript - 如何修复:使用 onClick 或使用 React 的 onKeyPress 触发 Meteor 方法两次
- swift - 在闭包内使用隐式数组值
- c - 使用 Bison 时将带标识符的公式转换为抽象语法树的错误
- r - 使用 lapply 连接列表元素
- css - SCSS:基于 calc() 取反/取反变量
- python - 3D 中的径向基函数(面向奇点矩阵)
- php - Iconv 在 phpunit 中返回不正确的字符串
- php - wordpress:日志中的php错误不断重复
- jquery - jQuery 根据显示的页面读取特定值
- android - Android recoder 声音,它捕捉到 java.io.FileNotFoundException