我正在尝试让我的 Discord 机器人回复用户,让他们知道如果他们在运行命令时发生错误,就会出错。我不确定我应该如何从命令索引文件中的命令消息中获取消息变量。
我已经尝试在命令文件中的索引.js文件中运行的函数中使用消息变量,但是当它运行时,它说未定义"message"。我怀疑这可能是我放.catch()
的地方。这是我正在使用的代码。
//This is the area in my index that handles errors
bot.on('error', (err, message) => {
console.error();
message.reply("error here, possibly a rich presence");
});
//Heres the function with the .catch()
http.request(options, function(res) {
var body = '';
res.on('data', function (chunk) {
body+= chunk;
});
res.on('end', function() {
var jsondata = JSON.parse(body);
var converteddate = new Date(jsondata.toTimestamp*1000)
console.log(converteddate)
var hours = converteddate.getHours();
var minutes = "0" + converteddate.getMinutes();
var finishedtime = hours + ':' + minutes.substr(-2);
message.reply(finishedtime + " EST.")
})
}).end()
.catch(err => bot.emit('error', err, message));
}
此操作的预期输出是运行命令,如果有任何错误,请通知用户。感谢您的帮助!
,所以首先你的"}"有问题(最后有一个不应该出现在这里(
然后,一个简单的示例如何捕获:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function error() {
await sleep(3000); // wait 5 sec for the sake of the example
throw 'I have a problem';
}
console.log('starting')
error().catch((err) => console.log('The error:',err))
我不确定.end()
是什么,但我认为你不需要它
所以在这里,你想做:
http.request(options, function(){
// do something
return 'text message'; // what you want to reply
}).catch((err) => err).then((msg) => message.reply(msg))
您可以访问该消息,因为在http.request
中未正确关闭。确保运行 linter 并美化代码,以便轻松发现代码中多余或未关闭的部分。
至于回复用户,您可以简单地执行以下操作:
message.author.send("There was an error: "+err);
我会尝试这样的事情:
http.request(options, (res) => {
let body = '';
res.on('data', (chunk) => {
body+= chunk;
});
res.on('end', () => {
const jsondata = JSON.parse(body);
const converteddate = new Date(jsondata.toTimestamp*1000)
console.log(converteddate)
const hours = converteddate.getHours();
const minutes = "0" + converteddate.getMinutes();
const finishedtime = hours + ':' + minutes.substr(-2);
message.reply(finishedtime + " EST.")
})
}).catch(err => message.author.send("There was an error: "+err.toString()));
如果你想做一个更全局的方法,我会创建一个errorHandler并导入它。但是,我没有看到任何特别的理由拥有一个通用的,因为您没有对它执行任何特定操作。