4

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);
5

4 Answers 4

4

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.")
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

thanks. this seems to work correctly while also defining this.stack where available. the only change i'll make in my own code is to also define this.name in the constructor.
Good suggestion; I've added that in (did it on the prototype since the name is the same for all instances, but it doesn't really matter).
Note: for fuller compatibility with IE, a few other things are needed; see stackoverflow.com/a/8460753/560114.
1

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)
      }
    }

Comments

0
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.