× {{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!
Olamide Soyoye
Olamide Soyoye
5.0
Senior Software Engineer & Server Administrator
As a seasoned engineer with over five years in complex software systems across multiple industries (such as Logistics systems, HealthTech, EdTech,...
Hire this Expert
Opeoluwa Lanre
Opeoluwa Lanre
5.0
An engineer with a keen understanding of cutting-edge technologies.
A full-stack software engineer passionate about crafting scalable, high-performing web solutions. With a strong focus on appealing user interfaces,...
Hire this Expert