Does Javascript fire an event for unhandled/uncaught exceptions?

Check out this Fiddle:

http://jsfiddle.net/xYsRA/1/

window.onerror = function (msg, url, line) {
    console.log("Caught[via window.onerror]: '" + msg + "' from " + url + ":" + line);
    return true; // same as preventDefault
};

window.addEventListener('error', function (evt) {
    console.log("Caught[via 'error' event]:  '" + evt.message + "' from " + evt.filename + ":" + evt.lineno);
    console.log(evt); // has srcElement / target / etc
    evt.preventDefault();
});


throw new Error("Hewwo world.  I crash you!!!");

throw new Error("Hewwo world.  I can only crash you once... :(");

Which prints:

Caught[via window.onerror]: 'Uncaught Error: Hewwo world.  I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:21
Caught[via 'error' event]:  'Uncaught Error: Hewwo world.  I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:26
ErrorEvent {lineno: 32, filename: "http://fiddle.jshell.net/xYsRA/1/show/", message: "Uncaught Error: Hewwo world.  I crash you!!!", clipboardData: undefined, cancelBubble: false…}
 fiddle.jshell.net:27\

Notes:

  • If you remove the “return true”https://stackoverflow.com/”evt.preventDefault()” lines, then after the error is logged, it will print on the JS console in the normal way.

  • Contrary to statements made above, window.onerror worked in all the browsers I tested. However, the addEventListener method is probably better anyways and provides richer semantics.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)