Last active
January 2, 2020 19:25
-
-
Save mbround18/a1fc9ec04b7e8cdd5a512b84667b4d90 to your computer and use it in GitHub Desktop.
Extendable custom errors for Typescript.
This file contains hidden or 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
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