subclass-error
Workaround for subclassing errors. Both instanceof
and stack
are functional.
Install
$ npm install --save subclass-error
Usage
var SubclassError = require('subclass-error');
var ClientError = SubclassError("ClientError", {statusCode:400});
var ForbiddenError = SubclassError("ForbiddenError", ClientError, {statusCode:403});
var clientErr = new ClientError ();
clientErr instanceof Error // true
clientErr instanceof ClientError // true
clientErr instanceof ForbiddenError // false
clientErr.statusCode // 400
var forbidErr = new ForbiddenError ();
forbidErr instanceof Error // true
forbidErr instanceof ClientError // true
forbidErr instanceof ForbiddenError // true
forbidErr.statusCode // 403
function hungry () {
throw new ForbiddenError ("wow, much forbidden, very subclass");
}
hungry();
/*
ForbiddenError: wow, much forbidden, very subclass
at hungry (filePath:19:8)
etc expected stack
*/
SubclassError(name, [error, properties])
Creates a new subclass of error
(if given) or Error
(by default). The instances of the new subclass will inherit data in the optional properties
parameter.
Why?
I couldn't find any existing solution in which both instanceof
and stack
worked as you would expect, back when I created this module.
License
MIT © David da Silva