Skip to content

Instantly share code, notes, and snippets.

@mbround18
Last active January 2, 2020 19:25
Show Gist options
  • Save mbround18/a1fc9ec04b7e8cdd5a512b84667b4d90 to your computer and use it in GitHub Desktop.
Save mbround18/a1fc9ec04b7e8cdd5a512b84667b4d90 to your computer and use it in GitHub Desktop.
Extendable custom errors for Typescript.
class CustomError extends Error {
public name = this.constructor.name;
constructor(message?: string, opts?: { name?: string }) {
super(message); // 'Error' breaks prototype chain here
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
}
}
// tslint:disable-next-line: max-classes-per-file
class SuperBadError extends CustomError {
constructor(message?: string) {
super(message);
}
}
// tslint:disable-next-line: max-classes-per-file
class EvenWorseError extends SuperBadError {
constructor(message?: string) {
super(message);
}
}
throw new EvenWorseError('Uhh ohh'); // => throws: EvenWorseError: Uhh ohh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment