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. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.
Can someone bring example of such function which is async and still throws? How and when do you catch the exception then?
More particularly. Do they refer to such function:
try
{
obj.someAsync("param", function(data){
console.log(data);
});
}catch(e)
{
}
Now normally I know above doesn't make sense -because when the callback executes, try
block could have been already exited.
- But what kind of example does the excerpt from documentation refer to? If async method throws as they say it, where, when and how should I handle it? (or maybe if you show such function can you show where in its doc it says how to handle it as mentioned on the quote?)
afaik there are three ways a async function could "throw"; and how to catch each of these:
These are the most common async errors you'll come along; well, the first one is just a plain bug in an async mothod.
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 withawait
keyword.Examples:
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:
And the operational errors you handle like this:
Now, if you have a function that doesn't take a callback but returns a promise:
Then you handle the error like this:
or, while using
await
: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.