Nicely throwing an error in gulp task

2019-02-21 21:40发布

问题:

I am creating a gulp task which might fail under certain circumstances.

gulp.task('favicon', function () {
  try {
    require('child_process').execSync('icotool --version');
  } catch( e ) {
    var err = new Error( 'Unix bash and icotool required for generating favicon' );
    throw err;
  }

  return gulp.src('', {read: false})
    .pipe(shell([
      './generate-favicon.sh'
    ]));
});

When running my task via gulp and running into the error, the error will be presented rather ugly. I would like to present the error in a way as it is done by e.g. jslint gulp-util's PluginError.

It actually works to just create a PluginError there and throw it but that doesn't seem quite right. Another solution not that nice would be to set

err.showStack = false;

for at least a little nicer error output. A gulp.task.Error would be nice.

回答1:

From what I've seen its not great to throw an error from gulp. But I found this blog entry that I used to work for me.

http://gotofritz.net/blog/geekery/how-to-generate-error-in-gulp-task/

Edit: gulp-util has been deprecated. Instead, use the plugin-error package.

My Example:

var gulp = require('gulp');
var error = require('plugin-error');
gulp.task('deploy', function(cb) {
  if(typeof(specialId) === 'undefined') {
    var err = new PluginError({
      plugin: 'deploy',
      message: 'specialId is empty.'
    });
  }
}