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.
- Nodejs | Automatic restart NodeJs server with nodemon
- Node | URL.resolve(from,to) API
- Node.js | dns.resolve() Method
- Node.js | dnsPromises.resolve() Method
- Node.js | path.resolve() Method
- How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
- JQuery deferred.resolve() method
- Scala | Finally Exceptions
- Scala | Try-Catch Exceptions
- Exceptions Vs Errors in PHP
- Raising Exceptions in Ruby
- PHP | Predefined Exceptions
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Cowsay in Nodejs using Requests library
- Nodejs | Web Crawling using Cheerio
- Web-Socket in NodeJS
- Signup Form Using Nodejs and MongoDB
- Dockerizing a simple Nodejs app
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.