After refactoring custom errors for ES6 in a large public library (pg-promise), I'm getting some strange reports that the custom errors may not instantiate correctly in some special cases, ones that I haven't been able to reproduce, after lots of attempts.
Could someone with experience in implementing custom errors, please tell me if the refactoring that was done is 1:1 correct, or if I've missed something.
Original ES5 Code
function CustomError(errCode) {
var temp = Error.apply(this, arguments);
temp.name = this.name = 'CustomError';
this.stack = temp.stack;
this.code = errCode;
}
CustomError.prototype = Object.create(Error.prototype, {
constructor: {
value: CustomError,
writable: true,
configurable: true
}
});
CustomError.prototype.toString = function () {
console.log('errCode:', this.code);
};
CustomError.prototype.inspect = function () {
return this.toString();
};
Refactored ES6 Code:
class CustomError extends Error {
constructor(errCode) {
super();
Error.captureStackTrace(this, CustomError);
this.code = errCode;
}
}
CustomError.prototype.toString = function () {
console.log('errCode:', this.code);
};
CustomError.prototype.inspect = function () {
return this.toString();
};
Both examples are required to work the same under any Node.js 4.x and later, instantiated as:
const error = new CustomError(123);
console.log(error);
According to a bug report, sometimes such a type is supposedly created without the right this context, or more accurately, the error says: can't use 'code' of undefined that's inside toString.
UPDATE
After looking at this article: Custom JavaScript Errors in ES6, and its example:
class GoodError extends Error {
constructor(...args) {
super(...args)
Error.captureStackTrace(this, GoodError)
}
}
it seems that passing in the arguments like that is what I am missing. But how can I update my CustomError class correctly to do the same, considering that:
- Syntax
...argsdoesn't work in Node.js 4.x, so I cannot use it - I need to combine it with the existing custruction parameters, such as
errCode
super()should besuper(arguments).super(...arguments)?thiscontext from being passed correctly.