SBB
SBB

Reputation: 8970

Javascript get Window Error Code

I am trying to figure out if there is a piece of Javascript that can be used to get the current javascript error in the window if there is one.

Internally, we have several websites that users from all over use. Some of them use the same hardware and systems as us where as others user VM's where the environments are different.

In short, we get a lot of support issues where a tool isn't working and we have to explain how to check for a JS error in IE.

I'm wanting to make a Bookmarklet they can have in their toolbar and when they experience an issue, it checks to see if there is a window error and then I can do something with it.

I know there is window.onerror=function(msg, url, linenumber){} but thats when an error happens. I am looking for a way to check for an error at any time when the user clicks on the bookmarklet.

Upvotes: 0

Views: 367

Answers (2)

nfleury
nfleury

Reputation: 165

The bookmarklet doesn't seems to be the best approach here, because when the user would click on it, it will be too late... the error has already occured .

Unless the error changes the state of something on the page on what you can rely in your bookmarklet ...

I think the best way to handle this issue is before it happens, it means handling it on the page where it is occuring ...

The error reporting should be part of the application

Upvotes: 0

Halcyon
Halcyon

Reputation: 57729

onerror isn't good enough. It gives you a message, a file and a line number. No stack trace, no argument inspection etc. It also catches errors thrown by third party code such as buggy Skype plugins.

What you want to do is wrap all your code in your own custom error handler function.

wrap_try_catch(function () {
    do_stuff();
})();

A try-catch across asynchronous functions doesn't work so make sure to wrap all the callbacks:

add_event(obj, "click", function () {});

function add_event(obj, what, callback) {
    obj.addEventListener(what, wrap_try_catch(callback));
}

Similarly you will want to wrap setTimeout and setInterval if you ever use them.

If you're smart you can even figure out how to make stacktraces capture over asynchronous calls so you can see where an xmlhttprequest initiated (rather than seeing onreadystatechange as the origin).


Using this approach you can implement active error reporting by having the catch implement an error reporting request. You can send an error digest message back to your server so you can log all errors.

The impact of always wrapping these functions is quite large, especially if you haven't got anything set up like this. It's certainly possible though.


This works even in very old versions of IE. We used to have a version that worked in IE6. Our lowest supported version now is IE9 so we can use to more features.

I think IE supports stacktraces as for IE10. Chrome and Firefox have supported it since forever.

Upvotes: 1

Related Questions