I'm trying to create a discord bot with the help of node.js In which I need to call a function that may return discord API errors I handle them like this
interaction.user.send("Hi")
.catch(() => {return interaction.reply("...");
console.log("shouldnt run if an error accured")
However whenever that API error accurse the return statement unlike normally does not stop the code execution. How do I stop the console.log statement in this code from executing when the exception accurse ?
the js is asynchronous so it puts the request of API in execution queue(not wait for response from api) and continue its execution that's why your console statement is running even if the error occurs.
interaction.user.send("Hi")
.then(() => {
// do whatever you want when it succeed
})
.catch((error) => {
// handle error
});
you can also checkout async await for the same.
As @ParthPatel indicates, interation.user.send() is returning a Promise which may not be rejected immediately upon error. Statements such as your console.log() will run before an error has a chance to occur and be caught.
However, these days there is the async await syntax you can use, which may help you simplify your code a bit depending on what you're trying to do.
try {
await interaction.user.send("Hi");
console.log('Shouldn\'t run if error occurred.');
} catch(e) {
interaction.reply('...');
}
Note that you can only use await inside of an async function, declared like this:
async function doSomething() {
// Do something here...
}
You can find more information here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await