0

I have followed the recommended solutions found at this question, but I am still seeing errors which break my watchers.

Given a watcher like this:

var through = require('through2');
var watch   = require('gulp-watch');

gulp.task('catchall', function() {
  return watch('gulpfile.js')
    .pipe(through.obj(externalFunc))
    .on('error', function(err) {
      console.log('Inside error handler:', err);
    });
});

With externalFunc defined as:

function externalFunc(file, enc, done) {
  throw new Error("I have been compromised - Abort mission!");
}

I would expect to see output of:

[10:52:51] Starting 'catchall'...
[10:52:53] gulpfile.js was changed
Inside error handler: I have been compromised - Abort mission!

Instead, I get no output from externalFunc, and instead get standard error output and a stacktrace:

[10:52:51] Starting 'catchall'...
[10:52:53] gulpfile.js was changed

/my/path/to/gulpfile.js:27
  throw new Error("I have been compromised - Abort mission!");
        ^
Error: I have been compromised - Abort mission!
    at DestroyableTransform.externalFunc [as _transform] ....

Most importantly, the watcher crashes.

Why does this error not get trapped by the on('error') listener, and what can I do in a gulp watcher to handle these errors without exiting?

Community
  • 1
  • 1
asfallows
  • 5,998
  • 6
  • 29
  • 48

1 Answers1

1

It's not getting trapped into the error listener, because as you said, this is not a stream error.

You're actually throwing an error to your node process which runs gulp, and not catching it, so it behaves as an uncaughtException and completely crash everything, without waiting for the error handler you've set to do its work.

Just for the demo, but not recommended, you can do something like this:

process.on('uncaughtException', function (er) {
  console.error('Throwing error:', er);
});

The error will be logged and your gulp watch will still run.

I may advice you to have a look to Node Domains to handle your errors safety, though I don't know if it's really a bad practice to use uncaughtException in something like gulp.

Preview
  • 35,317
  • 10
  • 92
  • 112