vrijdag 2 mei 2014

Error Handling for minified javascripts.

Why we minify

Javascript is often minified for production. This is also called 'uglification' sometimes. It means your javascript  is written like one long line.

What is the problem?

Minification can sometimes cause errors. It's hard to see if you made an error, or the minifier.
Sometimes an error just happens. We're not perfect.
In a minified file you'd get an error in your console like:
 Uncaught ReferenceError: faultyReference is not defined script.js: 2
When line 2 is 4000 characters long, it's a little heavy. Especially since most minifyers will also minify the variable faultyReference to something like: a132.


New standard fixes the problem

In the new standard for the window.onError event you don't just get a line, but also a column.
You can generate an error message for yourself:
 Uncaught ReferenceError: faultyReference is not defined script.js: line 2, col 3704
Now you know exactly where to debug...

Tell me how

Ok!
  1. start of 2014 this was working in Chrome. I don't know about other browsers, but if all else fails, develop in Chrome (I think it's the best development browser anyway) 
  2. before you execute any other script add something this:
 window.onerror=globalErrorListener;  
 function globalErrorListener(msg, url, line, col, obj)   
 {  
      console.log('--' + msg + ' ' + url + ': line ' + line  
      + ', col ' + col);  
 }  

Now in your console, you'll find the exact column where the error occured.
The obj is the stack, you can also log that, just add it to the string.

Tadaaa! And thank you chrome for implementing so fast. Hope this helps someone, it sure helped me!
more about this