Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Last active September 5, 2022 13:51
Show Gist options
  • Save richardscarrott/f054b60c235516f3529c14541486306f to your computer and use it in GitHub Desktop.
Save richardscarrott/f054b60c235516f3529c14541486306f to your computer and use it in GitHub Desktop.
Modern VError
interface TErrorOptions<Info, Cause> {
readonly msg?: string;
readonly info?: Info;
readonly cause?: Cause;
}
class TError<Info, Cause extends Error> extends Error {
public info?: Info;
public cause?: Cause;
constructor({ msg, cause, info }: TErrorOptions<Info, Cause>) {
super(msg, cause ? { cause } : undefined);
if (typeof info !== "undefined") {
this.info = info;
}
}
}
const error1 = new TError({ msg: "Expected foo" });
console.error("error1", error1);
const error2 = new TError({
msg: "Expected foo to be a string",
info: { foo: 123 },
});
console.error("error2", error2);
const error3 = new TError({
msg: "Expected foo",
info: { hello: "world" },
cause: new TError({ info: { goodbye: "world" } }),
});
console.error("error3", error3);
@richardscarrott
Copy link
Author

Now just need to wait for tooling to catch up with cause...

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