Skip to content

Instantly share code, notes, and snippets.

@kxxoling
Created September 15, 2020 00:23
Show Gist options
  • Save kxxoling/c714b58bb31fd3d4e67da3ae06f07eda to your computer and use it in GitHub Desktop.
Save kxxoling/c714b58bb31fd3d4e67da3ae06f07eda to your computer and use it in GitHub Desktop.
在Typescript里extends Error的终极方案
// 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