Defining custom errors – NodeJS

23 / Jun / 2014 by Kushal Likhi 1 comments

Any well written piece of code should be defensive by nature with defensive error handling understanding that things could go wrong. Things would be great if we can define our own custom error classes which we can pass or throw in order to distinguish various errors. Custom error constructors helps in:

  • ⇒   Identifying which error was thrown via compliance with instanceof
  • ⇒   Standardize error message format and abstract message building at a central place making it more DRY.
  • ⇒   Encapsulate additional data and information.
  • ⇒   More readable, manageable and streamlined Error Handling.


Building My Custom Error Class (Constructor)

Suppose we need to define a custom error named ValueOutOfRangeError which we will produce in case the values passed/retrieved are not within a specific range.

Lets see what all we need to do in order to define custom errors:

STEP 1: Make a file which will define the error.

Create a file with the name ValueOutOfRangeError.js. You can give any other name to the file, but its best recommended practice to name the file with the name of the constructor/class they export.

STEP 2: Add a basic constructor function.

Make a constructor function which takes the desired arguments and sets the message property of the object. Then export it.
[javascript]
//FILE ValueOutOfRangeError.js
"use strict";
/**
* Error Class ValueOutOfRangeError
* */
function ValueOutOfRangeError(propertyName, actualValue, rangeMin, rangeMax) {
//Set the name for the ERROR
this.name = this.constructor.name; //set our function’s name as error name.

//Define error message
this.message = [
"Property with name |",
propertyName ,
"| contains the value",
actualValue,
"which is outside the range:",
rangeMin, "to", rangeMax
].join(" "); //Concat and make a string.
}

//Export the constructor function as the export of this module file.
exports = module.exports = ValueOutOfRangeError;

[/javascript]

STEP 3: Inherit from native Error class.

Lets inherit from the Error native constructor such that our new custom error constructor is an actual error object.
[javascript]
//FILE ValueOutOfRangeError.js
"use strict";

//Utils module loaded
var util = require(‘util’);

/**
* Error Class ValueOutOfRangeError
* */
function ValueOutOfRangeError(propertyName, actualValue, rangeMin, rangeMax) {

/*INHERITANCE*/
Error.call(this); //super constructor
Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object

//Set the name for the ERROR
this.name = this.constructor.name; //set our function’s name as error name.

//Define error message
this.message = [
"Property with name |",
propertyName ,
"| contains the value",
actualValue,
"which is outside the range:",
rangeMin, "to", rangeMax
].join(" "); //Concat and make a string.
}

// inherit from Error
util.inherits(ValueOutOfRangeError, Error);

//Export the constructor function as the export of this module file.
exports = module.exports = ValueOutOfRangeError;

[/javascript]

STEP 4: Yeahh! All done. We have our first custom-error file in place:).

Using the custom-errors!

Now lets see how we can use our ValueOutOfRangeError class which we defined above.
[javascript]
//Load the custom error.
var ValueOutOfRangeError = require("./ValueOutOfRangeError");

//THROWING EXAMPLE
if(/*error check fails*/) throw new ValueOutOfRangeError("theAwesomeProperty", data.theAwesomeProperty, 10, 100);

//EXAMPLE RETURN VALUE
if(/*error check fails*/) callback(new ValueOutOfRangeError("theAwesomeProperty", data.theAwesomeProperty, 10, 100));

[/javascript]

Hope that helps!! 🙂

FOUND THIS USEFUL? SHARE IT

comments (1 “Defining custom errors – NodeJS”)

Leave a Reply

Your email address will not be published. Required fields are marked *