On 06/12/2013 07:50 AM, Mohamed Ashraf wrote:
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?
Some of my thoughts are:
* Try/catch has a performance penalty * We need to be able to easily turn off the error reporting feature * Some/most function names in the stack trace are going to be useless as the production js code is minified. * The line numbers in the file will not be of much help either, I guess, unless we change the way that the files are minified (like forcing line breaks every few hundred characters). * If we do want the stack traces, given that we use jQuery, we could tap into it and whip up our own traces. For example (completely untested code):
var lastException; (function ($) { var bind = $.fn.bind; $.fn.bind = function () { try { throw new Error; } catch (exception) { lastException = exception; } bind.apply({}, arguments); }; })(jQuery);
Later, lastException can be accessed from window.onerror. Of course, we'd have to tap into quite a few functions.
To me it sounds like window.onerror is the winner here.
Bye, Rouslan