Skip to content

Instantly share code, notes, and snippets.

@noahmiller
Created May 15, 2014 16:54
Show Gist options
  • Save noahmiller/61699ad1b0a7cc65ae2d to your computer and use it in GitHub Desktop.
Save noahmiller/61699ad1b0a7cc65ae2d to your computer and use it in GitHub Desktop.

Revisions

  1. noahmiller created this gist May 15, 2014.
    57 changes: 57 additions & 0 deletions gulpfile-error-handling.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    var gulp = require('gulp');
    var gutil = require('gulp-util');
    var jshint = require('gulp-jshint');

    // Command line option:
    // --fatal=[warning|error|off]
    var fatalLevel = require('yargs').argv.fatal;

    var ERROR_LEVELS = ['error', 'warning'];

    // Return true if the given level is equal to or more severe than
    // the configured fatality error level.
    // If the fatalLevel is 'off', then this will always return false.
    // Defaults the fatalLevel to 'error'.
    function isFatal(level) {
    return ERROR_LEVELS.indexOf(level) <= ERROR_LEVELS.indexOf(fatalLevel || 'error');
    }

    // Handle an error based on its severity level.
    // Log all levels, and exit the process for fatal levels.
    function handleError(level, error) {
    gutil.log(error.message);
    if (isFatal(level)) {
    process.exit(1);
    }
    }

    // Convenience handler for error-level errors.
    function onError(error) { handleError.call(this, 'error', error);}
    // Convenience handler for warning-level errors.
    function onWarning(error) { handleError.call(this, 'warning', error);}

    var testfiles = ['error.js', 'warning.js'];

    // Task that emits an error that's treated as a warning.
    gulp.task('warning', function() {
    gulp.src(testfiles).
    pipe(jshint()).
    pipe(jshint.reporter('fail')).
    on('error', onWarning);
    });

    // Task that emits an error that's treated as an error.
    gulp.task('error', function() {
    gulp.src(testfiles).
    pipe(jshint()).
    pipe(jshint.reporter('fail')).
    on('error', onError);
    });

    gulp.task('watch', function() {
    // By default, errors during watch should not be fatal.
    fatalLevel = fatalLevel || 'off';
    gulp.watch(testfiles, ['error']);
    });

    gulp.task('default', ['watch']);