Aug 26, 2013

Client side error logging

Everybody uses some analytics service to know how users uses its site. Some programmers even use custom events for this.

Generally it is good idea to know also if your user go out because of js error on your site.

Error logging on client

When something happen on development site programmer usually open developer console and look at errors, but if this happen for remote user we cannot ask each to open console and send us errors.

window.onerror - it is js DOM event handler that catch all programming errors. Some examples of errors:

// syntax error
<script>{</script>

// uncaught exception
<script>throw "some message"</script>

(i think anyone can suggest even more)

window.onerror handler has 3 arguments:

window.onerror = function(message, url, line) {
// message - it is some description of this error
// url - it is url of script that cause error
// line - it is line number in script where error happen
}

Simple example at jsfiddle on clicking button we can see in console messages:

So this is all we need to handle all errors. Second thing it is how to report errors.

On client we have a lot of choices where and how to send requests. For example i will use my tracking example from previous post. I need to include loading code in head as early as possible to get errors in other scripts:

<script>
window.onerror = function(message, url, line) {
 __it("error", message, url, line)
}
</script>

Of course i understand that almost everyone prefer to use something more popular and advanced than just analytics from some blog post. Google analytics has special category for exceptions and someone will write something like this:

window.onerror = function(message, url, line) {
  ga('send', 'exception', {
   'exDescription': 'Error "' + message + '" at '+ url + ' on line ' + line
  });
}

As a basic and free solution this is enough. But also need to say that exists a lot of paid services that solve similar problem but with some nice interface and more advanced features (I do not want publish its url, but if someone need i will add).

No comments:

Post a Comment