Last active
July 3, 2022 16:59
-
-
Save sstur/8477282f576f08f3caa56f6697881ae6 to your computer and use it in GitHub Desktop.
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
| function createErrorSubclass<T = string>( | |
| name: string, | |
| getMessage: (param: T | undefined) => string | undefined = (input) => | |
| input === undefined ? undefined : String(input), | |
| ErrorClass: new () => Error = Error, | |
| ) { | |
| if (!name.endsWith('Error')) { | |
| throw new Error(`Invalid name "${name}"`); | |
| } | |
| return Object.defineProperties( | |
| class extends ErrorClass { | |
| constructor(param?: T, options?: { cause?: Error }) { | |
| // @ts-expect-error | |
| super(getMessage(param), options); | |
| } | |
| get name() { | |
| return name; | |
| } | |
| get [Symbol.toStringTag]() { | |
| return name; | |
| } | |
| }, | |
| { | |
| // Defining the name property here is only necessary because we're | |
| // using an anonymous class | |
| name: { value: name, configurable: true }, | |
| }, | |
| ); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example here.