Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Catch tasks in GruntJS

Is there a way to catch when a GruntJS task fails and act upon it?

The --force flag doesn't help, because I need to know if something broke along the way, and do something about it.

I tried some arrangement similar to a try-catch, however it doesn't work. That is because grunt.registerTask pushes tasks into a queue - the execution is not synchronous.

  grunt.registerTask('foo', "My foo task.", function() {
    try {
      grunt.task.run('bar');
    } catch (ex) {
      // Handle the failure without breaking the task queue
    }
  });

Creative javascript ideas are welcome as well as GruntJS know-how.

like image 225
pilau Avatar asked Jan 18 '15 11:01

pilau


1 Answers

This ugly beast should work for you:

  grunt.registerMultiTask('foo-task', 'my foo task', function() {
    try {
      console.log(this.data);
      throw new Error('something bad happened!');
    } catch (e) {
      console.log('Ooops:', e);
    }

    return true;
  });

  grunt.registerTask('foo', 'Runs foo.', function() {
    grunt.config('foo-task', {
      hello: 'world'
    });
    grunt.task.run('foo-task');
  });

Run it via: grunt foo

Output:

Running "foo" task

Running "foo-task:hello" (foo-task) task
world
Ooops: Error: something bad happened!
    at Object.<anonymous> 

    <stacktrace here>    

Done, without errors.
like image 197
scthi Avatar answered Nov 19 '22 19:11

scthi