Working with window.onerror

Want to have your own window.onerror handlers? Here's how.

The information here is not Errorception-specific. It describes a way to attach multiple window.onerror handlers.

window.onerror is a little weird. It's not an Event in the common sense. It's stuck in the DOM Level 1 days — remember the ugliness of button.onclick?

In the DOM Level 1 event model that window.onerror uses, there can only be one event handler assigned at a time. That's because .onWhatever = function() {...} is a function assignment, and there can only be one function assigned to an event at a time.

This means that if you have your own window.onerror defined, you will override Errorception's handler. This will cause Errorception to completely stop recording errors!

Thankfully, JavaScript is amazing malleable. You can easily work around this problem by using the following little trick.

var oldOnError = window.onerror;

window.onerror = function() {
	if(oldOnError) oldOnError.apply(this, arguments);	// Call any previously assigned handler

	// The rest of your code

The code above checks if there was a previously defined window.onerror, and simply calls it before proceeding. Using this pattern, you can keep adding additional handlers to window.onerror as you please, without worrying about clobbering other code.

In fact, Errorception itself does this too, to avoid clobbering any previously defined window.onerror. It's right in the tracking snippet!