Skip to content

Instantly share code, notes, and snippets.

@sstur
Last active July 3, 2022 16:59
Show Gist options
  • Select an option

  • Save sstur/8477282f576f08f3caa56f6697881ae6 to your computer and use it in GitHub Desktop.

Select an option

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

sstur commented Jul 3, 2022

Copy link
Copy Markdown
Author

Example here.

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