Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Exception Handling

What is the best technique for catching ALL exceptions thrown within JavaScript?

Obviously, the best technique is to use try...catch. But with ansynchronous callbacks and so forth, that can get tricky.

I know IE and Gecko browsers support window.onerror, but what about Opera and Safari?

Here are a bunch of test-cases that I would like to have a central exception handling solution for:

// ErrorHandler-Test1
var test = null;
test.arg = 5;
// ErrorHandler-Test2
throw (new Error("Hello"));
// ErrorHandler-Test3
throw "Hello again";
// ErrorHandler-Test4
throw {
    myMessage: "stuff",
    customProperty: 5,
    anArray: [1, 2, 3]
};
// ErrorHandler-Test5
try {
    var test2 = null;
    test2.arg = 5;
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test6
try {
    throw (new Error("Goodbye"));
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test7
try {
    throw "Goodbye again";
} catch(e) {
    ErrorHandler.handleError(e);
}
// ErrorHandler-Test8
try {
    throw {
        myMessage: "stuff",
        customProperty: 5,
        anArray: [1, 2, 3]
    };
} catch(e) {
    ErrorHandler.handleError(e);
}

If you think of any other test-cases, please mention them. Several of these cases mention a ErrorHandler.handleError method. This is just a suggested guideline when using try...catch.

like image 202
harley.333 Avatar asked Oct 15 '08 17:10

harley.333


3 Answers

If you use a library like jQuery for assigning all your event handlers, you can use a combination of window.onerror and wrapping the jQuery event handler code and on ready function with an error handling function (see: JavaScript Error Tracking: Why window.onerror Is Not Enough).

  • window.onerror: catches all errors in IE (and most errors in Firefox), but does nothing in Safari and Opera.
  • jQuery event handlers: catches jQuery event errors in all browsers.
  • jQuery ready function: catches initialisation errors in all browsers.
like image 169
Karl Avatar answered Oct 17 '22 20:10

Karl


WebKit (Safari, Chrome, etc) now appears to support onerror.

Original post: As far as I know, WebKit/Safari does not support the onerror event. Which is a damn shame.

like image 21
eyelidlessness Avatar answered Oct 17 '22 20:10

eyelidlessness


Actually, the jquery approach isn't so bad. See:

http://docs.jquery.com/Events/error#fn

and:

$(window).error(function(msg, url, line){
  $.post("js_error_log.php", { msg: msg, url: url, line: line });
});
like image 7
adamfisk Avatar answered Oct 17 '22 20:10

adamfisk