There are two approaches to resolve unhandled exceptions in Node.js that are discussed below:
Note: However, be careful not to use try-catch in asynchronous code, as an asynchronously thrown error will not be caught.
Approach 2: Using Process: A good practice says, you should use Process to handle exception. A process is a global object that provides information about the current Node.js process. The process is a listener function that is always listening to the events.
Few events are:
- Multiple Resolves
- Unhandled Exception
- Rejection Handled
- Uncaught Exception
The most effective and efficient approach is to use Process. If any uncaught or unhandled exception occurs in your code flow, that exception will be caught in code shown below:
The above code will be able to handle any sort of unhandled exception which occurs in Node.js.