Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
Node.js catch statement return does not stop executing

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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!