Wednesday, November 11, 2015

Helpful error handling in JavaScript

Hi,

today I tried to develop an error handling in javascript (more exact: angularjs, but this is as good as meaningless here) that makes sense and is helpful. The following solution is built and tested in Chrome.

First of all: javascript support try/catch blocks we can use by throwing errors


1
2
3
4
5
try {
  throw new Error('Whoops!');
} catch (e) {
  alert(e.name + ': ' + e.message);
}

(see: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Error )
... but this is not the thing I meant...

I wanted to create a central function (error callback, error output method) that can be used to gather further information during development time (e.g. as an error callback for a bad web service rest request; as a usable function to call if an internal object state is unknown => a situation happens that should never happen).

... so I did the following:

1
2
3
4
5
6
7
8
            $scope.writeError = function (response) {
                if (true) { // DEBUG
                    console.error('error', response);
                    console.trace();
                    debugger;
                    throw new Error('error');
                } 
            };

writeError has an if (line 2) which disables the javascript-console information fast. In angularjs it is easily possible to build this "if" depending on angularjs-constants that can be configured central in a application configuration section.

line 5 sets a coded breakpoint in the javascript console (see: http://stackoverflow.com/questions/10050465/set-a-javascript-breakpoint-in-code-in-chrome / I adapted the jsfiddle to http://jsfiddle.net/hBCH5/70/ ); 3 and 4 writes the data (and all its properties) to the console; line 6 throws an exception that can be caught in code and shows similar information to the console.

Attention: the removal of the throw statement can change the application execution logic if try/catch blocks were used outside.

kind regards,
Daniel

// Update

I should have mentioned 2 things:
- there is window.onerror where you can assign an event handler
- there are frameworks like jsnlog ( jsnlog.com ) that sends the error to a server where they can be monitored centrally (angularjs compatible)

No comments: