How to resolve unhandled exceptions in Node.js ?

There are two approaches to resolve unhandled exceptions in Node.js that are discussed below:

Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

try {
      
    // The synchronous code that
    // we want to catch thrown
    // errors on
    var err = new Error('Hello')
    throw err
} catch (err) {
      
    // Handle the error safely
    console.log(err)
}

chevron_right


Note: However, be careful not to use try-catch in asynchronous code, as an asynchronously thrown error will not be caught.

filter_none

edit
close

play_arrow

link
brightness_4
code

try {
    setTimeout(function() {
        var err = new Error('Hello')
        throw err
    }, 1000)
}
catch (err) {
      
    // Example error won't be caught
    // here... crashing our application
    // hence the need for domains
}

chevron_right


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:



  • Disconnect
  • Exit
  • Message
  • Multiple Resolves
  • Unhandled Exception
  • Rejection Handled
  • Uncaught Exception
  • Warning

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:

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

process.on('uncaughtException', function(err) {
  
    // Handle the error safely
    console.log(err)
})

chevron_right


The above code will be able to handle any sort of unhandled exception which occurs in Node.js.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.