Skip to content Skip to sidebar Skip to footer

When Do Async Methods Throw And How Do You Catch Them?

From node doc: A handful of typically asynchronous methods in the Node.js API may still use the throw mechanism to raise exceptions that must be handled using try / catch. The

Solution 1:

The async methods like the one from your example usually throw for programmer errors like bad parameters and they call the callback with error for operational errors.

But there are also async functions in ES2017 (declared with async function) and those signal errors by rejecting the promise that they return - which turn into a thrown exception when you use them with await keyword.

Examples:

functionx(arg, cb) {
    if (!arg) thrownewError('Programmer error: bad arguments');
    setTimeout(() => {
        cb(newError('Operational error: something bad happened'));
    }, 2000);
}

Now when you use it you usually don't want to handle programmer errors - you want to fix them. So you don't do this:

try {
    x();
} catch (err) {
    // Why should I handle the case of bad invocation// instead of fixing it?
}

And the operational errors you handle like this:

x(function (err) {
    if (err) {
        // handle error
    } else {
        // success
    }
});

Now, if you have a function that doesn't take a callback but returns a promise:

functiony() {
    returnnewPromise((res, rej) =>setTimeout(() =>rej('error'), 2000));
}

Then you handle the error like this:

y().catch(error => {
    // handle error
});

or, while using await:

try {
    await y();
} catch (err) {
    // handle error
}

For more info on the difference between operational errors and programmer errors see:

For more info on the promises and async/await see the links in this answer.

Solution 2:

afaik there are three ways a async function could "throw"; and how to catch each of these:

  • as any other function (aka. someone messed up): I'd not catch these cases because they should not be in my code, and catching such errors makes it harder to find and fix em.

functionfoo(){
//someone messed up, better fixing than catching thisreturnnewProoooooooooomise((resolve) =>42);
}

try {
foo();
}catch(err){
console.error(err);
}
  • Promises:

functionfoo(){ returnPromise.resolve('bar') }

foo().then(value => value =========> 'error')
.catch(err => {
	console.error(err);
	return"fixedValue";
});
  • And Nodes callback syntax/pattern:

functionfoo(value, callback){
setTimeout(function(){
	if(Math.random() < .5){
		callback("I don't like to", undefined);
	}else{
		callback(null, value * 2);
	}
}, 500);
}

foo(21, function(err, data){
if(err){
	//no try..catch at allconsole.error(err);
}else{
	//do whatever with data
}
})

These are the most common async errors you'll come along; well, the first one is just a plain bug in an async mothod.

Post a Comment for "When Do Async Methods Throw And How Do You Catch Them?"