pitu
pitu

Reputation: 820

is it good to use try catch in nodejs

i just want to know is it good to use try catch in nodejs. for example i am using crypto modules of node js, for encryption & decryption. so i am handling any error while encryption/ decryption in try catch is it a good practice ?????

Upvotes: 5

Views: 12014

Answers (1)

Zlatko
Zlatko

Reputation: 19569

If your encryption/decryption calls are synchronous (depends on the library, module, function you use), try/catch is ok to use it, otherwise depending on how you've used it, it might be useless.

Try/catch is ok to catch a programming error or buggy code, for example from libraries you don't know might be buggy.

Like:

try {
  libraryLib.encrypt(notSureIfThisIsAValidParam);
} catch (err) {...}

You're not sure if the user/password are set, and you're not sure if the crypto library might fail, so you wrap it.

But try/catch also creates a new execution context, copies over scopes and all, and this is a costly operation, in terms of CPU time. It means that you should try to avoid try/catch in hot code paths.

Logic/business errors in Node are usually handled with error-first callback patterns (or Promises, or similar). Generally you'd only use try/catch if you expect programmer errors (ie. bugs), and other patterns for errors you expect.

Of course, this is just one line of reasoning, and I generally see a lot of intentional throw clauses (meant to use with try/catc) in Node code written by Java converts. But that might be specific to me, so YMMV.

Upvotes: 8

Related Questions