Petr Marek
Petr Marek

Reputation: 735

Correct way to catch error when await for function in Javascript

I can't catch reject in my function. I have searched at google, but I haven't found solution, so please help me with this piece of code:

async function errorFunc(){
    setTimeout(() => {
        return Promise.reject("Any error occured!");
    }, 1000);
}
async function main(){
    await errorFunc().catch((error)=>{
        console.log("E in catch:", error);
    });
    
    try{
        await errorFunc();
    }catch(e){
        console.log("E in try-catch:", e);
    }
}

main();

No one of that catch (in main() function) works...In console, there is simply printed (twice) this error message:

Uncaught (in promise) Any error occured!

I want to catch that error (or better say promise rejection). How can I do that in my main() function?

Thanks!

Upvotes: 3

Views: 86

Answers (3)

Milad Raeisi
Milad Raeisi

Reputation: 467

You must return a Promise from your function

async function errorFunc(){
   return new Promise((resolve,reject)=>{
   setTimeout(() => {
      return reject("Any error occured!");
   }, 1000);
  })
}

async function main(){
   await errorFunc().catch((error)=>{
      console.log("E in catch:", error);
   });

   try{
      await errorFunc();
   }catch(e){
      console.log("E in try-catch:", e);
   }
}

Upvotes: 0

French Noodles
French Noodles

Reputation: 124

I think it printed the same error twice, because in the second function:

try{
        await errorFunc();
    }catch(e){
        console.log("E in try-catch:", error);
    }
}

you printed "error" but caught "e", I didn't understand the issue that much but I suppose that that's the reason it printed twice,

maybe swap "error" with "e" to print the other error caught

Upvotes: 1

王仁宏
王仁宏

Reputation: 396

async function errorFunc(){
    return new Promise((resolve, reject) => setTimeout(() => reject("Any error occured!"), 1000))
}

this is what you want.


setTimeout(callback, ms)

callback will be exec in global, no one catch it.

Upvotes: 3

Related Questions