How to Handle Gulp Watch Errors with Plumber

I've been using Gulp a lot lately and loving it's approach (streams (which I'm stilling wrapping my head around) and the fact that it's "just code," as compared to Grunt's big ol's config file).

Basically, I feel like it's easier to read/write/modify/wrap-your-head-around (once you understand how the async tasks work and get (at least a little bit) of an understanding of streams).

The Problem

But one thing that was driving me nuts was that whenever something that you're watching via gulp.watch, if there is an error, then it breaks something about all the streams in Gulp and effectively stops watching files.

For example, let's say you have a simple gulp file that watches all your *.scss files, and you save a file with something "illegal" in it and the sass compile task run in the background throws an error. Then if you try and save it again... nothing happens. You have to start Gulp again, which is super annoying.

Plumber Saves the Day!

So I tried researching this quite a bit, Googling stuff, but I could not figure out how to keep Gulp Watch from crashing. I found some really long threads on the subject, but it was hard to follow (lots of stream talk), but eventually, I was doing something completely unrelated and looking over someone else's gulpfile.js online and they were using this plugin I'd seen before called "Gulp Plumber."

I had heard of it before, but the description on the npm page ("This plugin is fixing issue with Node Streams piping") is a little vague. But thankfully, the gulpfile.js I was looking at had a little comment: "prevents gulp.watch from crashing."

I'm like, "that's exactly what I've been trying to do!" I install gulp-plumber, and use it according to the plugin's usage and lo and behold, when I purposedly throw an error in my scss, gulp.watch keeps running! Yay. Now I can fix that error and save and the world makes sense again.

Hope that this helps someone else.

Also, here's a little trick to help you know when there is an error:

var onError = function (err) {  
  gutil.beep();
  console.log(err);
};

gulp.task('styles', function () {  
  gulp.src('scss/style.scss')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(rubysass())
    .pipe(gulp.dest('dist/'));
});

Now when there is an error, the terminal will "beep," alerting you that there was a problem, so you can check out the error and fix it.