Max SchmittMS
22nd January 2014

Prevent gulp.js from crashing on error

gulp.js is a new task runner / build system that seems to do many things better than others. I started playing around with it for a new experiment that uses browserify as a module loader.

Old gulpfile

var gulp = require('gulp')
var browserify = require('gulp-browserify')
gulp.task('scripts', function() {
return gulp
.src('js/main.js')
.pipe(browserify({ debug: true }))
.pipe(gulp.dest('dist'))
})
gulp.task('default', ['scripts'], function() {
gulp.watch('js/**/*.js', ['scripts'])
})

Now this worked really well, but whenever I had any errors in my Javascript-files that were supposed to be processed by browserify, the whole process crashed and stopped the watcher.

You can prevent gulp.js and the watcher-script from stopping when errors occur, by handling these errors. To do this, simply add an error listener to where your errors might be thrown.

gulp.src('...')
.pipe(functionThatMightThrowAnError())
.on('error', onError)
function onError(err) {
console.log(err)
this.emit('end')
}

Emitting the end event inside your error handler is key. The resulting gulpfile, that prevents gulp from crashing when errors are thrown, looks like this:

New gulpfile.js

var gulp = require('gulp')
var browserify = require('gulp-browserify')
gulp.task('scripts', function() {
return gulp
.src('js/main.js')
.pipe(browserify({ debug: true }))
.on('error', onError)
.pipe(gulp.dest('dist'))
})
gulp.task('default', ['scripts'], function() {
gulp.watch('js/**/*.js', ['scripts'])
})
function onError(err) {
console.log(err)
this.emit('end')
}
Image of my head

About the author

Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.