Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

How to catch the the Async error in JavaScript?

Sometime I write a NodeJS and use the framework from NPM. I can't catch the error if the error is throw inside the framework. For example,

function willThrowError(){
    setTimeout( async _ => {
        await wait(1); //promise that will resolve after one second
        process.nextTick( _ => { 
            throw new Error('Error throw')
        });
    }, 200)
};

I have try to wrap it within try-catch block and using domain module to catch this error but it doesn't work. If there is any solution to catch the error?

I try the below methods but all fail.

try {
    willThrowError();
} catch ( error ){
    console.log("'Try Catch' catch the error");
}

const domain = Domain.create();

domain.on('error', error => {
    console.log("'Domain' catch the error");
});

domain.run( willThrowError );

Comments