× {{alert.msg}} Never ask again
Receive New Tutorials
GET IT FREE

ReactJS Tip: Show exceptions from Flux Dispatcher callbacks

– {{showDate(postTime)}}

Flux is a frontend application architectural pattern by Facebook. Being an architectural pattern, it’s largely a do-it-yourself kind of deal. That is, except for an implementation of the Dispatcher, which is provided in the flux package on npm.

The Dispatcher accepts callbacks with its register method, and invokes those callbacks anytime an action is dispatched to it. One curious behavior of the Dispatcher, though, is that it will eat any exception that occurs in a callback, and keep chugging along. Presumably, this is so that one failing callback doesn’t cause the whole application to blow up. It has the effect, though, of making debugging incredibly painful.Here’s how to get exceptions to show up in your console again, assuming you have a subclass of Dispatcher called AppDispatcher, as in the TodoMVC example. First, we’ll define a function that logs errors of the function it’s passed:
var vomitify = function(f) {
  return function() {
    try {
      f.apply(this, arguments);
    } catch(e) {
      console.error(e.stack);
    }
  }
};

Note: Here, we reference the console object, which will fail spectacularly in older versions of IE when you don’t have the developer console open. Make sure you don’t run this in production, or if you do, make sure to redefine console safely.

Now, we’ll override the dispatch method of AppDispatcher to use vomitify.

 

var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');

var AppDispatcher = assign(new Dispatcher(), {

  handleViewAction: function(action) {
    console.log(action);
    this.dispatch({
      source: 'VIEW_ACTION',
      action: action
    });
  },

  handleServerAction: function(action) {
    console.log(action);
    this.dispatch({
      source: 'SERVER_ACTION',
      action: action
    });
  },

  register: function(f) {
    return Dispatcher.prototype.register.call(this, vomitify(f));
  }

});

module.exports = AppDispatcher;

That’s it! Now your exceptions will be logged to the console again. Happy debugging!


Chris LaRose is a software developer who is familiar with many languages such as Python, C, Java, Ruby, JavaScript, and SQL. This article was originally posted at his blog.




Questions about this tutorial?  Get Live 1:1 help from React experts!
Behnam Anjomruz
Behnam Anjomruz
5.0
Full stack Java Developer
I have been helping multiple companies since 2008. So probably somewhat qualified to answer the same. Being a code mentor, I will have the...
Hire this Expert
Rahul Choudhary
Rahul Choudhary
5.0
Wordpress - Shopify - Wocommerce Designer & Developer | 8 + Years
Senior Developer with over 8 years of experience in web design and development. Proficient in HTML, CSS, SCSS, Bootstrap, JavaScript, PHP,...
Hire this Expert