Better Error Messages From Gulp Using Gulp-Util

Gulp is a streaming build system that can help automate and enhance your workflow. For example, at Base22, in one of our composite tasks, we use Gulp to create a directory structure, compile Less into standard CSS, copy static dependencies, minify JavaScript, compress images, run a simple HTTP server, and then watch for subsequent changes to files while we’re working. Gulp is easy to install, easy to learn, easy to configure, and I love it. But when it happens to bomb on a problem, it doesn’t always log information that you can actually make sense of. Luckily, there’s a Gulp plugin that can help you coax more troubleshooting info out of these errors.

Take the following Gulp error message, for example:

Example Problem – Useless Error Message

events.js:85 throw er; // Unhandled 'error' event ^ Error at new Parser (C:\git\frontend\node_modules\gulp-less\node_modules\less\lib\less\parser.js:333:27) at Object.less.render (C:\git\frontend\node_modules\gulp-less\node_modules\less\lib\less\index.js:18:22)

Pretty useless. The only thing one can discern from the error is that it has something to do with the less parser. But what? Who the #$@% knows.

But what if you could get the following instead?

Example Solution: Improved Error Message

[15:52:20] { [Error: Unrecognised input in file C:\git\frontend\dev\less\theme.less line no. 2449] type: 'Parse', message: 'Unrecognised input in file C:\\git\\frontend\\dev\\less\\theme.less line no. 2449', filename: 'C:\\git\\frontend\\dev\\less\\theme.less', index: 45319, line: 2449, callLine: NaN, callExtract: undefined, column: 17, extract: [ ' .btn-main-green {background-color: #7AB642; color:white; }', ' .btn-main-green: {background-color: #7AB642; color:white; }', ' .btn-main-green:hover {background-color: #2B872B; color:white;}' ], lineNumber: 2449, fileName: 'C:\\git\\frontend\\dev\\less\\theme.less', ...etc...

This error message is much improved. It tells us exactly which less file is failing the parser. It also tells us the precise failing line number, and it even gives us an extract of the CSS around that line number. Without even opening the file, we can see the erroneous colon after the CSS class, .btn-main-green: {.

How To…

The answer to this problem lies in the gulp-util plugin.

Install the plugin and also add it to your package.json file with the following command:

npm install --save-dev gulp-util

Next, add the following declaration to the top of your gulp.js file:

var gutil = require('gulp-util');

Finally, attach the following error handler to tasks (when you are compiling less, uglifying some code, or whatever):

.pipe(less().on('error', gutil.log))


.pipe(uglify().on('error', gutil.log))

With this little gem, you can now spend less time troubleshooting errors and more time creating works of art.