Open In App

Explain some Error Handling approaches in Node.js

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is an open-source JavaScript runtime environment. It is often used on the server-side to build API for web and mobile applications. A large number of companies such as Netflix, Paypal, Uber, etc use Node.js.

Prerequisites:

An error is any problem given out by the program due to a number of factors such as logic, syntax, timeout, etc. Error handling is an important part of Node.js and should be implemented carefully. In this tutorial let’s have a look at some approaches to handle errors, but first let’s set up our basic environment.

Create a file named error.js. This file will serve as a base for exploring the various methods.

Method 1: Using a try-catch block.

The catch block handles any exception raised by the code in the try block. 

Syntax:

try{
    // Code
}catch(error){
    // Error Handling
}

Example:

Javascript




try{
    const areYouAwesome = false;
    if(!areYouAwesome){
        throw new Error("We know you are awesome, 
                       we are having troubing with our code.")
    }
}catch(error){
    console.log(error.message);
}


Output:

We know you are awesome, we are having troubing with our code.

Method 2: Using try-catch while performing asynchronous operations

Asynchronous operations sometimes require the program to be halted while the data is retrieved. We can pair up async-await functions with try-catch blocks to handle errors. 

Syntax:

const myFunction = async () => {
    try{
        await operationWhichTakesTime()
    }catch(error){
        // Error handling
    }
}

Example:

Javascript




const delay = (wait) => {
    return new Promise(resolve => setTimeout(resolve, wait));
}
  
const awesomeFunction = async () => {
    try{
        await delay(2000)
        throw new Error("Error thrown after delay");
    }catch(error){
        console.log(error.message);
    }
}
  
awesomeFunction();


Output:

Error thrown after delay

Method 3: Using Promises

Promises are used to handle asynchronous operations in JavaScript. They are three states for a promise namely the pending state, the resolved state, and the rejected state. In the pending state, the promise is waiting for some other function or for some data to be retrieved. In the resolved state, the function has worked as it’s intended and the promise is resolved. In the rejected state, some error has crept up in the function and the promise is rejected.

Syntax:

promise().then((data) => {
    // Code
}).catch((error) => {
    // Error handler
})

Example:

Javascript




const awesomeFunction = (isAwesome) => {
    return new Promise((resolve, reject) => {
        if(isAwesome){
            resolve("You are awesome");
        }else{
            reject("We know you are awesome, 
                   we are having troubing with our code.")
        }
    })
  
awesomeFunction(false).then((message) => {
    console.log(message);
}).catch((error) => {
    console.log(error)
});


Output:

We know you are awesome, we are having troubing with our code.

Method 4: Using an event listener 

The process global object in Node.js can be used to listen for any uncaught exceptions that may have crept up in the program.

Syntax:

process.on('uncaughtException', error => {
    // Error Handling
    process.exit(1)
})

Example:

Javascript




process.on('uncaughtException', error => {
    console.log(error.message);
    process.exit(1) 
})  
  
const awesomeFunction = (isAwesome) => {
    if(!isAwesome){
        throw new Error("We know you are awesome, 
                     we are having troubing with our code.")
    }
  
awesomeFunction();


Output:

We know you are awesome, we are having troubing with our code.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads