I have a specific type of errors, which I always want to report with a track system, such as Sentry, or AppInsight. So I created a class inherited from Error, and now I want to call a function every time this error is thrown. I don’t want to do it manually in each and every try-catch clause, not to mention the fact that it’s easy to forget, and other devs can ignore it. How can I do it? Of course, I can put it into the constructor, but calling the side-effect there isn’t a good idea.
In this case, I’m going to report this issue:
class ExhaustiveCheckError extends Error {}
export function exhaustiveCheck(unreachableValue: never): never {
throw new ExhaustiveCheckError(
'Should not have reached here. Not all cases are covered'
);
}
Here it’s used to handle an error when using a switch case/if with data of an unexpected type from IO, for example, from the backend, or user input. I know it’s better to parse/validate data at boundaries with ZOD/Run-types, etc., but now it’s not possible to implement.
What other options do I have?