Created
September 15, 2020 00:23
-
-
Save kxxoling/c714b58bb31fd3d4e67da3ae06f07eda to your computer and use it in GitHub Desktop.
在Typescript里extends Error的终极方案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From https://zhuanlan.zhihu.com/p/113019880 | |
// 使用 BaseError 当作 base Error class | |
class BaseError extends Error { | |
constructor(message: string) { | |
super(message); | |
this.name = new.target.name; | |
if (typeof (Error as any).captureStackTrace === 'function') { | |
(Error as any).captureStackTrace(this, new.target); | |
} | |
if (typeof Object.setPrototypeOf === 'function') { | |
Object.setPrototypeOf(this, new.target.prototype); | |
} else { | |
(this as any).__proto__ = new.target.prototype; | |
} | |
} | |
} | |
// 使用例子 | |
class MyError extends BaseError { | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment