1

I have the following code:

var test = { 
  func1: function() {...},
  func2: function() {...},
  func3: function() {...}
};

Now, I want to be able to catch any exceptions that might be thrown inside of func1/2/3. Is there an elegant way to do this without having to insert a try catch in each function?

Each function makes a call to a 3rd party library, so using window.onerror just gives me a very generic Script error, which I can't really use (due to cross origin issue apparently).

The code executes within a WebBrowser control in WPF, where the browser is targeting IE10. I'm not allowed to use anything but pure javascript and jQuery.

Whenever an exception is caught I propagate it further on to the underlying viewmodel which then logs it on the server.

0

1 Answer 1

1

You could build yourself a reusable wrapper:

function wrap(f) {
    return function() {
        try {
            return f.apply(this, arguments);
        }
        catch (e) {
            errorHandler(e, f);
            throw e; // Or not, but if not, what would you return?
        }
    };
}

Then either:

var test = { 
  func1: wrap(function() {...}),
  func2: wrap(function() {...}),
  func3: wrap(function() {...})
};

or

var test = { 
  func1: function() {...},
  func2: function() {...},
  func3: function() {...}
};
Object.keys(test).forEach(function(key) {
    var func = test[key];
    if (typeof func === "function") {
        test[key] = wrap(func);
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

It works fine but I have an additional question. What if I want to place the Object.Keys... in another javascript file in another namespace. So we have ErrorHandler.js in which we have: var Helpers = { wrapAllFunctions: function(namespace) { Object.keys(namespace).forEach(.......)}...
In the above case it doesn't work by calling ErrorHandler.Helpers.wrapAllFunctions(test); Any idea why?
@DSF: JavaScript doesn't have namespaces. Many people use objects as namespaces, in which case the second example above (using forEach) works just fine -- for any functions referenced by properties in the object you pass it. If they're nested deeper, of course, you'd have to handle that.
So I should be able to say wrapAllFunctions(test); and it should work even though wrapAllFunctions() is in another file?
@DSF: Sure. We use functions from other files all the time. In your example above, you'd have to have ErrorHandler.Helpers = Helpers; somewhere, since Helpers is a variable (which I assume isn't a global).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.