Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include error details in unchecked Java exception #768

Merged
merged 1 commit into from
Nov 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 8 additions & 16 deletions java/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
<javaVersion>8</javaVersion>
<bouncyCastleVersion>1.78.1</bouncyCastleVersion>
<skipUnitTests>${skipTests}</skipUnitTests>
<pmdVersion>7.6.0</pmdVersion>
<pmdVersion>7.7.0</pmdVersion>
</properties>

<dependencyManagement>
Expand All @@ -55,7 +55,7 @@
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.2</version>
<version>5.11.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Expand Down Expand Up @@ -206,8 +206,8 @@
<showWarnings>true</showWarnings>
<compilerArgs>
<arg>-Xlint</arg>
<arg>-Xlint:-options</arg> <!-- Disable command line warnings, seen when
building against multiple releases: -->
<!-- Disable command line warnings, seen when building against multiple releases -->
<arg>-Xlint:-options</arg>
<arg>-Werror</arg>
</compilerArgs>
</configuration>
Expand Down Expand Up @@ -301,15 +301,6 @@
<goal>report-integration</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules />
</configuration>
</execution>
</executions>
</plugin>
<plugin>
Expand Down Expand Up @@ -453,13 +444,14 @@
<configuration>
<checkSkip>${skipUnitTests}</checkSkip>
<java>
<trimTrailingWhitespace />
<endWithNewline />
<trimTrailingWhitespace/>
<endWithNewline/>
<palantirJavaFormat>
<version>2.47.0</version>
<version>2.50.0</version>
<style>PALANTIR</style>
<formatJavadoc>false</formatJavadoc>
</palantirJavaFormat>
<removeUnusedImports/>
<licenseHeader>
<file>${project.basedir}/license-header.txt</file>
</licenseHeader>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
package org.hyperledger.fabric.client;

import io.grpc.StatusRuntimeException;
import java.io.CharArrayWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.List;
Expand All @@ -19,6 +18,8 @@
* more of those nodes. In that case, the details will contain errors information from those nodes.
*/
public class GatewayException extends Exception {
// Ignore similarity with unchecked GatewayRuntimeException - CPD-OFF

private static final long serialVersionUID = 1L;

private final transient GrpcStatus grpcStatus;
Expand Down Expand Up @@ -63,9 +64,7 @@ public void printStackTrace() {
*/
@Override
public void printStackTrace(final PrintStream out) {
PrintWriter writer = new PrintWriter(out);
printStackTrace(writer);
writer.flush();
new GrpcStackTracePrinter(super::printStackTrace, grpcStatus).printStackTrace(out);
}

/**
Expand All @@ -74,26 +73,8 @@ public void printStackTrace(final PrintStream out) {
*/
@Override
public void printStackTrace(final PrintWriter out) {
CharArrayWriter message = new CharArrayWriter();

try (PrintWriter printer = new PrintWriter(message)) {
super.printStackTrace(printer);
}

List<ErrorDetail> details = getDetails();
if (!details.isEmpty()) {
message.append("Error details:\n");
for (ErrorDetail detail : details) {
message.append(" address: ")
.append(detail.getAddress())
.append("; mspId: ")
.append(detail.getMspId())
.append("; message: ")
.append(detail.getMessage())
.append('\n');
}
}

out.print(message);
new GrpcStackTracePrinter(super::printStackTrace, grpcStatus).printStackTrace(out);
}

// CPD-ON
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
package org.hyperledger.fabric.client;

import io.grpc.StatusRuntimeException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.List;
import org.hyperledger.fabric.protos.gateway.ErrorDetail;

Expand All @@ -16,6 +18,8 @@
* more of those nodes. In that case, the details will contain errors information from those nodes.
*/
public class GatewayRuntimeException extends RuntimeException {
// Ignore similarity with checked GatewayException - CPD-OFF

private static final long serialVersionUID = 1L;

private final transient GrpcStatus grpcStatus;
Expand Down Expand Up @@ -44,4 +48,33 @@ public io.grpc.Status getStatus() {
public List<ErrorDetail> getDetails() {
return grpcStatus.getDetails();
}

/**
* {@inheritDoc}
* This implementation appends any gRPC error details to the stack trace.
*/
@Override
public void printStackTrace() {
printStackTrace(System.err);
}

/**
* {@inheritDoc}
* This implementation appends any gRPC error details to the stack trace.
*/
@Override
public void printStackTrace(final PrintStream out) {
new GrpcStackTracePrinter(super::printStackTrace, grpcStatus).printStackTrace(out);
}

/**
* {@inheritDoc}
* This implementation appends any gRPC error details to the stack trace.
*/
@Override
public void printStackTrace(final PrintWriter out) {
new GrpcStackTracePrinter(super::printStackTrace, grpcStatus).printStackTrace(out);
}

// CPD-ON
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2021 IBM All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.hyperledger.fabric.client;

import java.io.CharArrayWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.function.Consumer;
import org.hyperledger.fabric.protos.gateway.ErrorDetail;

class GrpcStackTracePrinter {
private final Consumer<PrintWriter> printStackTraceFn;
private final GrpcStatus grpcStatus;

public GrpcStackTracePrinter(final Consumer<PrintWriter> printStackTraceFn, final GrpcStatus grpcStatus) {
this.printStackTraceFn = printStackTraceFn;
this.grpcStatus = grpcStatus;
}

public void printStackTrace(final PrintStream out) {
PrintWriter writer = new PrintWriter(out);
printStackTrace(writer);
writer.flush();
}

public void printStackTrace(final PrintWriter out) {
CharArrayWriter message = new CharArrayWriter();

try (PrintWriter printer = new PrintWriter(message)) {
printStackTraceFn.accept(printer);
}

List<ErrorDetail> details = grpcStatus.getDetails();
if (!details.isEmpty()) {
message.append("Error details:\n");
for (ErrorDetail detail : details) {
message.append(" address: ")
.append(detail.getAddress())
.append("; mspId: ")
.append(detail.getMspId())
.append("; message: ")
.append(detail.getMessage())
.append('\n');
}
}

out.print(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2024 IBM All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/

package org.hyperledger.fabric.client;

import static org.assertj.core.api.Assertions.assertThat;

import com.google.protobuf.Any;
import com.google.rpc.Code;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.hyperledger.fabric.protos.gateway.ErrorDetail;
import org.junit.jupiter.api.Test;

abstract class CommonGatewayExceptionTest {
protected abstract Exception newInstance(StatusRuntimeException e);

@Test
void error_details_are_printed() {
List<ErrorDetail> details = Arrays.asList(
ErrorDetail.newBuilder()
.setAddress("ADDRESS1")
.setMspId("MSPID1")
.setMessage("MESSAGE1")
.build(),
ErrorDetail.newBuilder()
.setAddress("ADDRESS2")
.setMspId("MSPID2")
.setMessage("MESSAGE2")
.build());
Exception e = newInstance(newStatusRuntimeException(Code.ABORTED, "STATUS_MESSAGE", details));

ByteArrayOutputStream actual = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(actual)) {
e.printStackTrace(out);
}

List<String> expected = details.stream()
.flatMap(detail -> Stream.of(detail.getAddress(), detail.getMspId(), detail.getMessage()))
.collect(Collectors.toList());
assertThat(actual.toString()).contains(expected);
}

@Test
void message_from_StatusRuntimeException_is_printed() {
Exception e = newInstance(newStatusRuntimeException(Code.ABORTED, "STATUS_MESSAGE", Collections.emptyList()));

ByteArrayOutputStream actual = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(actual)) {
e.printStackTrace(out);
}

String expected = e.getCause().getLocalizedMessage();
assertThat(actual.toString()).contains(expected);
}

@Test
void print_stream_passed_to_printStackTrace_not_closed() {
Exception e = newInstance(newStatusRuntimeException(Code.ABORTED, "", Collections.emptyList()));

ByteArrayOutputStream actual = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(actual)) {
e.printStackTrace(out);
out.println("EXPECTED_SUBSEQUENT_MESSAGE");
}

assertThat(actual.toString()).contains("EXPECTED_SUBSEQUENT_MESSAGE");
}

private StatusRuntimeException newStatusRuntimeException(Code code, String message, List<ErrorDetail> details) {
List<Any> anyDetails = details.stream().map(Any::pack).collect(Collectors.toList());
com.google.rpc.Status status = com.google.rpc.Status.newBuilder()
.setCode(code.getNumber())
.setMessage(message)
.addAllDetails(anyDetails)
.build();
return StatusProto.toStatusRuntimeException(status);
}
}
Loading