Getting familiar with ES6 classes and came across some unexpected behaviour while trying to create custom errors (i.e. extending Error).
Below is the module (error.js) code:
class BadRequestError extends Error {
constructor( ...args ) {
super( ...args );
this.name = "BadRequestError";
}
}
exports.BadRequestError = BadRequestError;
Then when I use it as follows in node console, you can see I get false when I check if err instanceof Error...
The rest of the extension seems to be fine; I can check .name, .message, .stack etc. without issues.
> var error = require("./error");
undefined
> var err = new error.BadRequestError("This is a bad request");
undefined
> err.name
'BadRequestError'
> err.message
'This is a bad request'
> err.stack
'BadRequestError: This is a bad request\n at BadRequestError (C:\<hidden>\error.js:3:5)\n at repl:1:11\n at sigintHandlersWrap (vm.js:32:31)\n at sigintHandlersWrap (vm.js:96:12)\n at ContextifyScript.Script.runInContext (vm.js:31:12)\n at REPLServer.defaultEval (repl.js:308:29)\n at bound (domain.js:280:14)\n at REPLServer.runBound [as eval] (domain.js:293:12)\n at REPLServer.<anonymous> (repl.js:489:10)\n at emitOne (events.js:101:20)'
> err instanceof Error
false
> err instanceof error.BadRequestError
true
I would expect this to return true, but oddly it isn't. Is this correct behaviour or am I missing something? Any help/explanations would be greatly appreciated.