NodeJS Exception handling
Handling Exception In Node.Js
Node.js has 3 basic ways to handle exceptions/errors:
1. try-catch block
2. error as the first argument to a callback
3. emit an error event using eventEmitter
try-catch is used to catch the exceptions thrown from the synchronous code execution. If the caller (or the caller's caller, ...) used try/catch, then they can catch the error. If none of the callers had try-catch than the program crashes.
If using try-catch on an async operation and exception was thrown from callback of async method than it will not get caught by try-catch. To catch an exception from async operation callback, it is preferred to use promises.
Example to understand it better
callbacks are mostly used in Node.js as callback delivers an event asynchronously. The user passes you a function (the callback), and you invoke it sometime later when the asynchronous operation completes.
The usual pattern is that the callback is invoked as a callback(err, result), where only one of err and result is non-null, depending on whether the operation succeeded or failed.
emit For more complicated cases, instead of using a callback, the function itself can return an EventEmitter object, and the caller would be expected to listen for error events on the emitter.