指示构建失败的标准方法是抛出异常。ProblemReporter 通过允许抛出带有相关问题报告的异常来提供增强支持。
FailingTask.java
ProblemId id = ProblemId.create("sample-error", "Sample Error", StandardPlugin.PROBLEM_GROUP);
throw getProblems().getReporter().throwing((new RuntimeException("Message from runtime exception")), id, problemSpec -> {
problemSpec.contextualLabel("This happened because ProblemReporter.throwing() was called")
.details("This is a demonstration of how to add\ndetailed information to a build failure")
.documentedAt("https://example.com/docs")
.solution("Remove the Problems.throwing() method call from the task action");
});
这确保了构建失败与底层问题明确关联,并且这些问题得到适当传达给各种客户端。当使用 Problems API 报告构建失败时,所有客户端(Tooling API、CLI、Build Scan 等)都将可以访问该关联。
命令行界面
CLI 构建失败输出将包含有关问题的详细信息。错误消息和描述直接来自问题报告。如果问题报告包含解决方案或建议的操作,这些将显示在通用解决方案的位置。
AdditionalData 不包含在 CLI 输出中。
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':sample-project:myFailingTask'.
> Message from runtime exception
This happened because ProblemReporter.throwing() was called
This is a demonstration of how to add
detailed information to a build failure
* Try:
> Remove the Problems.throwing() method call from the task action
> Run with --scan to generate a Build Scan (Powered by Develocity).
BUILD FAILED in 0ms
Tooling API 客户端
Tooling API 客户端可以通过根构建操作上的 Failure 对象访问与构建失败相关的详细问题报告。要接收这些报告,客户端必须为 OperationType.ROOT 操作类型注册一个进度侦听器。然后,进度侦听器回调应检查操作结果是否为 FailureResult 类型,然后可以通过 Failure.getProblems() 访问相关问题。
此外,还有一种更方便的方式来访问失败详情。如果客户端使用 LongRunningOperation.withFailureDetails() 配置项目连接,Tooling API 会隐式订阅 ROOT 操作类型,并通过 GradleConnectionException.getFailures() 方法提供失败详情。