Open In App

How to set Error.code property in Node.js v12.x ?

Improve
Improve
Like Article
Like
Save
Share
Report

Setting setError.code property in Node.js v12.x or above is a bit complex process, but In this article, you will learn to do this in a very easy way.

Problem Statement: Sometimes we want to set the error code manually, we want to show our own error code instead of a pre-built error code when throwing an error.

Approach: We have to extend the prebuilt Error class and set code property according to our needs. Inside inherit class, we have to create a constructor which is used to set the error message. 

class manualError extends Error {
   constructor (message) {
       super(message);
       this.code = 'ERRORGEEK';
   }
}

We can set an error message by creating an object of the child class with an error message as a parameter.

let err = new manualError('opps!');

Example 1: Let’s see how to set an Error.code property in Node.js v12.x through this example. Follow the below steps: 

Step 1: Create and Open a project folder inside a code editor.

Step 2: Locate the project folder inside the terminal.

Step 3: Create a file app.js either manually or by typing the command

touch app.js

Step 4: Open the file inside the code editor.

Step 5: Write the following code:

Javascript




class manualError extends Error {
    constructor (message) {
        super(message);
        this.code = 'ERRORGEEK';
    }
}
  
let err = new manualError('opps!');
  
console.log(err);


Step 6: Inside the terminal type the command to run your script.

node app.js

Output:

 

Example 2: This is another example that shows how to set an Error.code property in Node.js v12.x through this example. Follow the below steps: 

Step 1: Create and Open a project folder inside a code editor.

Step 2: Locate the project folder inside the terminal.

Step 3: Create a file app.js either manually or by typing the command

touch app.js

Step 4: Open the file inside the code editor.

Step 5: Write the following code:

Javascript




class manualError extends Error {
    constructor (message) {
        super(message);
        this.code = 'ERRORGEEK';
    }
}
  
function checkEquality (a, b) {
    if (a === b) {
        console.log('numbers are equal');
    } else {
        let err = new manualError('numbers are not equal');
        throw err;
    }
}
  
checkEquality(12, 14);


Step 6: Inside the terminal type the command to run your script.

node app.js

Output:

 



Last Updated : 04 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments