Last Updated: February 25, 2016
· mrjoelkemp

Backbone.js: Better error visibility

Here's a quick tip that should save you some hair and a few debugging hours when dealing with errors generated during Backbone.Events pub/sub.

Monkeypatch Backbone.trigger with a try/catch to see errors that were previously trapped like so:

var oldTrigger = Backbone.trigger;
Backbone.trigger = function () {
  try {
    oldTrigger.apply(Backbone, arguments);
  } catch (e) {

It's a simple wrapping that should be placed at the top of your app's initialization. Note the use of console.error (Supported in IE8 and every other browser) which will print the error object to the console. If you're using a javascript error monitoring tool (I personally use <a href="https://musculahq.appspot.com/" target="_blank" rel="nofollow">Muscula</a>), they'll log it without a problem.


Originally written here: http://mrjoelkemp.com/2013/11/backbone-js-better-error-visibility/

Say Thanks

2 Responses
Add your response



over 1 year ago ·
1973614 10152332782865736 8196949058027341535 o copy

Indeed, interesting idea.

Couple cautions with this approach:

1) Performance concerns. http://flippinawesome.org/2013/09/30/rethinking-javascripts-trycatch/. Just the presence of a try/catch block in a section of javascript code can have performance implications (meaning even if no exception is thrown)

2) In IE8 + 9, "console" is only available when you have developer tools open. If an error occurs and you haven't opened dev tools, you'll get an error trying to use it. Mostly I'm saying this in reference to your comment "Supported in IE8 and every other browser"

over 1 year ago ·