Reputation: 4591
I am trying to implement a simple js logging. After testing the code below I have found it behaves differently based on browser.
changing return to true, false, or removing the return all have different effects. Does anyone know how to avoid this. I want to be able to catch errors and log them, but I also want to maintain the browsers error handling.
window.onerror = function () {
alert('error caught!');
// Basically here I fire a Google Analytics force event track call to log the error
return false;
}
Alternatively if someone knows a better approach to logging client side js errors...
Chrome - return false - shows error in console Safari - return false - does not show error in console
** funny enough switching to return true gives you the exact opposite results. Not sure about IE etc.
Upvotes: 2
Views: 1467
Reputation: 2051
If you want the line number of the error in IE, I'm pretty sure your only option is window.onerror
because when IE throws an exception in a try...catch
block, it doesn't contain the line number. That said, every browser has a different implementation of the exception thrown in a try...catch
block - some provide a full stack trace which you can't get from window.onerror
in any browser. I didn't know about the particular quirk you've discovered, but I do know that exception handling is just about the most inconsistently implemented thing across all browsers, and it doesn't even stay the same within each browser; if I remember right, Opera changed their exception class in Opera 10 and broke something I had written to parse an exception in Opera.
Suffice to say you've discovered the hell that is exception handling in JavaScript and the only way around it is browser detection and branching accordingly to do the right thing for each browser. I've been looking for a good library to deal with exceptions in JavaScript and abstract the browser differences from me, but so far I haven't found one.
Upvotes: 1