Skip to content

Instantly share code, notes, and snippets.

@sstur
Last active July 3, 2022 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstur/8477282f576f08f3caa56f6697881ae6 to your computer and use it in GitHub Desktop.
Save sstur/8477282f576f08f3caa56f6697881ae6 to your computer and use it in GitHub Desktop.
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 },
},
);
}
@sstur
Copy link
Author

sstur commented Jul 3, 2022

Example here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment