vitaly-t
vitaly-t

Reputation: 25840

Custom ES6 JavaScript Error issue

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:

Upvotes: -1

Views: 142

Answers (1)

pishpish
pishpish

Reputation: 2614

I believe this is equivalent to your ES5 code

class CustomError extends Error {

    constructor( errCode ){
        super(...arguments);
        this.name = "CustomError";
        this.code = errCode;
    }

    toString(){
        console.log('errCode:', this.code);
    }

    inspect(){
        return this.toString();
    }

}

You can replace super(...arguments) with

super();
Error.apply(this, arguments);

Upvotes: 1

Related Questions