[FE] instanceof自定義Error

在生產(chǎn)環(huán)境中使用Babel,發(fā)現(xiàn)instanceof在自定義Error的情況出錯了,
用例如下:

// User defined base class
class Base { }
class Sub extends Base { }

let sub = new Sub;
console.assert(sub instanceof Sub);    //pass
console.assert(sub instanceof Base);

// Builtin base class, such as Error
class UserDefinedError extends Error { }

let e = new UserDefinedError;
console.assert(e instanceof UserDefinedError);    //failed
console.assert(e instanceof Error);

這里有篇文章提到了這一點:
Why doesn't instanceof work on instances of Error subclasses under babel-node?

Extending builtin types like Array and Error and such has never been supported in Babel.
It is perfectly valid in a real ES6 environment, but there are requirements to make it work that are very difficult to transpile in a way that is compatible with older browsers.

方案1:

function ExtendableBuiltin(cls) {
    function ExtendableBuiltin() {
        cls.apply(this, arguments);
    }
    ExtendableBuiltin.prototype = Object.create(cls.prototype);
    Object.setPrototypeOf(ExtendableBuiltin, cls);

    return ExtendableBuiltin;
}

class UserDefinedError extends ExtendableBuiltin(Error) { }

let sub = new UserDefinedError;
console.assert(sub instanceof UserDefinedError);    //pass

參考:
Extending builtins like Error and Array doesn't work in 6.x

方案2:

function MyError(message) {
    this.name = 'MyError';
    this.message = message || 'Default Message';
    this.stack = (new Error()).stack;
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

try {
    throw new MyError();
} catch (e) {
    console.log(e.name);     // 'MyError'
    console.log(e.message);  // 'Default Message'
}

try {
    throw new MyError('custom message');
} catch (e) {
    console.log(e.name);     // 'MyError'
    console.log(e.message);  // 'custom message'
}

參考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容