Following this other question about tracking errors in JS [1], I'm trying to use something similar to window.onerror to track only the errors pertinent to the context of my class or Web Component, since my components are meant to be used in other websites.
Is that possible right now?
(If there are any services that do this right now, it would also be nice to know.)
For example, I would like to track all the errors coming from my class or its inheritors:
abstract class Trackable extends HTMLElement {
override connectedCallback() {
this.onerror = (
message?: string,
file?: string,
line?: number,
column?: number,
error?: Error
) => {
console.log(error.cause);
};
}
}
However, this doesn't seem work. And if I use window instead of this, then any errors on the window will run into this listener, which is not what I want.
References
As mentioned in one of the comments above, you could wrap all functions in a try/catch to watch for errors and track them. There's a couple ways you could go about this programmatically, but there's some pitfalls to them.
The first option would be to take all the class functions in the constructor and re-assign them with a new, wrapped version of the function. There's a couple ways to do this, one where you explicitly do each function, and another where you iterate over all the keys and then wrap them, something along the lines of this:
The downside here is that this is a little hard to type if you're using TS, and it can cause issues if there's things you don't want to wrap, or if people extend the class and do weird things with it (This can also end up attempting to wrap things that aren't actually class methods).
Another option is to use the new decorators to achieve the same wrapping, but this requires transpilation as decorators aren't at full support in most places yet. This allows you more control over which functions get wrapped and which ones don't, but again has issues if a consumer of your library extends or does weird stuff with your class.
The last option is to manually add that try/catch yourself to all the functions you want logged.