views:

58

answers:

2

I'm trying to write to a global error handler that can work in Chrome and Safari. WebKit browsers don't support window.onerror, so I'd like to find a way to iterate through all of the functions in my code and encapsulate them in try - catch blocks, passing any exceptions to my custom error handling code. Does anyone know of an effective way to accomplish this?

+1  A: 

You can use jQuery aop. Something like

jQuery.aop.around( {target: window, method: /.*/}, 
  function(invocation) {
    var result;
    try{
      result = invocation.proceed(); 
    }
    catch( e ){
      myHandler();
    }
    return result;
  }
);

And in case you're unused to AOP, here's the wiki explanation.

Stefan Kendall
A: 

That's pretty easy. Just put all the functions in an array and call them all in individual try/catch.

function catchall(arr) { // array of functions to call
    for (var i=0; i<arr.length; i++) {
        try {
            arr[i]();
        } catch(e) {
            // pass the error to your global err handler
        }
    }
}

If your functions require arguments, wrap them in individual closures.

function square(a) {
    return a * 2;
}

catchall([
    function() {
        return square(8);
    },
    function() {
        throw new Error("Catch me"); // gotta have a fail case
    }
]);

If your functions require scoping, use Function.apply. If your functions call asynchronous methods, it becomes a little trickier because the callbacks will always be invoked in a new scope (which is tied lexically to where it was defined, but exceptions won't be caught by the try/catch for the original scope).

Michiel Kalkman