Gulp, Browserify, and error handling

The front-end stack is an ever growing list of processes and dependencies. These tools typically improve your process, but in some cases can hinder it. An often overlooked piece of build processes is error handling. Nothing can be more frustrating than silent errors in your build process.

One such build tool we use on a daily basis is Gulp.js and Browserify. Browserify allows us to create bundles of JavaScript modules. Gulp is a streaming task runner that that can process a directory of files as we change them. In short, we can write modular JavaScript in an automated fashion.

The problem is, without proper error handling, an error in your code will silently break your automated Gulp process. This forces you to switch to your terminal window to restart the process – interrupting your workflow. For example, the code below will silently kill your Gulp process.

browserify(file) .bundle() .pipe(source(basename)) .pipe(gulp.dest(config.paths.build));

Is there a way around this? Yes! If you put in place proper error handling on the Browserify process it won't bubble up into breaking your Gulp task. If you scan the Browserify docs you'll find .on(event, callback()). This can be used to check for an error event and then do something once that event is fired.

browserify(file) .bundle() .on('error', function(err){ console.log(err.stack);
notifier.notify({
  'title': 'Compile Error',
  'message': err.message
});

}) .pipe(source(basename)) .pipe(gulp.dest(config.paths.build));

Within our check for on('error') we are doing a couple different things. First we're printing the error stack to the terminal. This is very useful, it will print the error message as well as the function that broke and it's preceding functions. I also added the node-notifier package to my Gulp process, this lets us create desktop notifications from our Gulp task. So, we are also creating a notification that prints an error message we can debug.

Now that our Browserify errors are handled, our Gulp task won't break! If we run into an error we can simply fix, save, and Gulp will re-bundle as if nothing happened.

Code

Read This Next