How do I catch errors in synchronous functions in node.js?

In asynchronous functions, we can simply catch the error in the callback. For example:

Async func:

fs.readdir(path, function(err){
    //catch error
)

      

Since synchronous functions do not have a callback, how can I catch errors?

Synchronization function:

fs.readdirSync(path);           //throws some error

      

One way is to use a try catch block:

try{
    fs.readdirSync(path);
}
catch(err){
    //do whatever with error
}

      

Is there any other way to do this? If so, which one is better?

+3


source to share


1 answer


Is there any other way to do this?



No how do you do it. Typically, you have all your main logic in try

, and then just handle exceptional conditions (errors) in catch

. (And cleaning in finally

.)

+5


source







All Articles