n0w
n0w

Reputation: 85

Correct way to create custom errors in javascript

What is the correct way to define a custom error in JavaScript?

Searching through SO I've found about 6 different ways to define a custom error, but I'm unsure as to the (dis)advantages to each of them.

From my (limited) understanding of prototype inheritance in JavaScript, this code should be sufficient:

function CustomError(message) {
   this.name = "CustomError";
   this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);

Upvotes: 4

Views: 2127

Answers (4)

Amarpreet Singh
Amarpreet Singh

Reputation: 21

This script depicts all the possible mechanisms for creating and using custom errors in JavaScript.

Also to get a complete understanding, it's essential to have an understanding of prototypal inheritance and delegation in JavaScript. I wrote this article which explains it clearly. https://medium.com/@amarpreet.singh/javascript-and-inheritance-90672f53d53c

I hope this helps.

function add(x, y) {
      if (x && y) {
        return x + y;
      } else {
        /**
         * 
         * the error thrown will be instanceof Error class and InvalidArgsError also
         */
        throw new InvalidArgsError();
        // throw new Invalid_Args_Error(); 
      }
    }

    // Declare custom error using using Class
    class Invalid_Args_Error extends Error {
      constructor() {
        super("Invalid arguments");
        Error.captureStackTrace(this);
      }
    }

    // Declare custom error using Function
    function InvalidArgsError(message) {
      this.message = `Invalid arguments`;
      Error.captureStackTrace(this);
    }
    // does the same magic as extends keyword
    Object.setPrototypeOf(InvalidArgsError.prototype, Error.prototype);

    try{
      add(2)
    }catch(e){
      // true
      if(e instanceof Error){
        console.log(e)
      }
      // true
      if(e instanceof InvalidArgsError){
        console.log(e)
      }
    }

Upvotes: 1

Matt Browne
Matt Browne

Reputation: 12419

Usually I just use throw new Error(...), but for custom errors I find the following code works pretty well and still gives you stack traces on V8, i.e. in Chrome and node.js (which you don't get just by calling Error.apply() as suggested in the other answer):

function CustomError(message) {
    // Creates the this.stack getter
    if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor)
    this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
CustomError.prototype.name = 'CustomError';

For more info, see these links:

What's a good way to extend Error in JavaScript?

https://plus.google.com/+MalteUbl/posts/HPA9uYimrQg

Upvotes: 2

Scott
Scott

Reputation: 3765

The simplest of course, and in my opinion, the best to use unless you need more complex error reporting/handling is this:

throw Error("ERROR: This is an error, do not be alarmed.")

Upvotes: 4

alessandrio
alessandrio

Reputation: 4370

function CustomError() {
   var returned = Error.apply(this, arguments);
   this.name = "CustomError";
   this.message = returned.message;
}
CustomError.prototype = Object.create(Error.prototype);
//CustomError.prototype = new Error();

var nie = new CustomError("some message");

console.log(nie);
console.log(nie.name);
console.log(nie.message);

Upvotes: 0

Related Questions