Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 330
Petr Marek Avatar asked Jun 14 '26 03:06

Petr Marek


2 Answers

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.

like image 107
王仁宏 Avatar answered Jun 17 '26 21:06

王仁宏


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

like image 21
French Noodles Avatar answered Jun 17 '26 21:06

French Noodles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!