I was researching about how to catch errors in javascript. I faced a problem. due to the way javascript works for a try block to catch an error it has to be within the context of execution which means in the following code:
try { function f(){ throw new Error() } } catch (e) {}
calling f(); the error will not be caught in the try block. essentially what this means is that if we need to catch the errors using try and catch blocks we need to wrap the inside of every function with a try block. I am not sure how feasible is this idea but it I am sure it would reduce code readability.
The other option is using window.onerror which allows you to hook a function that gets executed whenever an uncaught exception occurs. This is obviously much simpler and less invasive and has an upside that errors in any context anywhere will still be reported to the hooked function. But there is a catch. which is that window.onerror does not provide a stacktrace because it is executed in a different context from the error itself. what it has access to is the line number, file name and exception message.
so my question is which method should I use, the surrounding all functions by try blocks or using the window.onerror callback method? how important is the stacktrace?