Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch errors in synchronous functions in node.js?

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

Async func:

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

As synchronous functions don't have callback, how can I catch errors?

Sync func:

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

One way is to use try catch block:

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

Is there any other way to do that? If yes, then which one is better?

like image 463
manish Avatar asked May 21 '15 07:05

manish


1 Answers

Is there any other way to do that?

No, that's how you do it. Typically you have all your main logic in the try, and then just handle exceptional conditions (errors) in the catch. (And cleanup in the finally.)

like image 100
T.J. Crowder Avatar answered Oct 28 '22 13:10

T.J. Crowder