Bee
Bee

Reputation: 12513

How to modify error message after executing a command via a Gradle task

I'm implementing a Gradle Java plugin which registers below task.

TaskProvider<Exec> taskProvider = project.getTasks().register("spectralTask", Exec.class);
taskProvider.configure(exec -> {
    exec.executable("spectral");
    exec.args("lint");
});

When the output of the executed command is an error, this is what I get.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:spectralTask'.
> Process 'command 'spectral'' finished with non-zero exit value 1

This error message is not very helpful. I want to fix it. Is there a way to do below?

  1. Print a custom error message.
  2. Print the exact error message given by the executed command.

Upvotes: 0

Views: 117

Answers (1)

Mateusz Kasprzak
Mateusz Kasprzak

Reputation: 11

To achieve this one option is to overwrite exec's standardOutput and/or errorOutput with ByteArrayOutputStream and re-throwing the exception with modified message from it.

For example:

def execOutput = new ByteArrayOutputStream()
try {
    return this.project.exec({
        it.errorOutput = execOutput
        it.standardOutput = execOutput       
        // rest of exec's config
    })
} catch (exception) {
    // Will print task's output as part of the error message
    throw new ExecException(exception.message + LineSeparator.SYSTEM + execOutput.toString())
} finally {
    // Preserve the logs in the task output
    print execOutput.toString()
}

Upvotes: 1

Related Questions