× {{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!
RajhaRajesuwari S
RajhaRajesuwari S
5.0
Senior AI-Focused Full-Stack Dev | 19+ Yrs | Python, PHP, .NET
⏱ MY WORK HOURS : 7AM to 11 PM INDIAN STANDARD TIME . 16 HOURS A DAY :) I’m a senior full-stack developer with 19+ years of real-world experience...
Hire this Expert
Lele
Lele
5.0
Passion for clean and reusable code
Senior software engineer with 10 years of experience. Started out in the trenches coding, fueled by solving tricky problems and getting hooked on...
Hire this Expert