How do I get a correct backtrace for a custom error class in NodeJS?

Evan P. picture Evan P. · Dec 10, 2011 · Viewed 9.4k times · Source

My understanding for the "right" way to make a custom Error class in JavaScript is something like this:

function MyError(message) {  
    this.name = "MyError";  
    this.message = message || "Default Message";  
}  
MyError.prototype = new Error();  
MyError.prototype.constructor = MyError;

(Code snippet mooked from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error.)

With NodeJS, if I try to check for an error of this type like:

var err = new MyError("whoops");
assert.ifError(err);

...the backtrace will show the context of the Error object I created at compile time to be the prototype for MyError, not the MyError object I created with "new MyError()".

Is there some way that I can get the correct backtrace data for the actual error, rather than the prototype?

Answer

Jay Kumar picture Jay Kumar · Dec 10, 2011

We need to invoke the super function - captureStackTrace

var util = require('util');

function MyError(message) {
  Error.call(this); //super constructor
  Error.captureStackTrace(this, this.constructor); //super helper method to include stack trace in error object

  this.name = this.constructor.name; //set our function’s name as error name.
  this.message = message; //set the error message
}

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

UPDATE:

You can use this node module to extend Error types easily https://github.com/jayyvis/extend-error