For the sake of completeness -- just because none of the previous answers mentioned this method -- if you are working with Node.js and don't have to care about browser compatibility, the desired effect is pretty easy to achieve with the built in inherits
of the util
module (official docs here).
For example, let's suppose you want to create a custom error class that takes an error code as the first argument and the error message as the second argument:
file custom-error.js:
'use strict';
var util = require('util');
function CustomError(code, message) {
Error.captureStackTrace(this, CustomError);
this.name = CustomError.name;
this.code = code;
this.message = message;
}
util.inherits(CustomError, Error);
module.exports = CustomError;
Now you can instantiate and pass/throw your CustomError
:
var CustomError = require('./path/to/custom-error');
// pass as the first argument to your callback
callback(new CustomError(404, 'Not found!'));
// or, if you are working with try/catch, throw it
throw new CustomError(500, 'Server Error!');
Note that, with this snippet, the stack trace will have the correct file name and line, and the error instance will have the correct name!
This happens due to the usage of the captureStackTrace
method, which creates a stack
property on the target object (in this case, the CustomError
being instantiated). For more details about how it works, check the documentation here.