Skip to content

Commit 322333a

Browse files
committed
Add StatusProto.toStatusException overload to accept Throwable
1 parent 167a203 commit 322333a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

protobuf/src/main/java/io/grpc/protobuf/StatusProto.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,25 @@ public static StatusException toStatusException(
103103
return toStatus(statusProto).asException(toMetadata(statusProto, metadata));
104104
}
105105

106+
/**
107+
* Convert a {@link com.google.rpc.Status} instance to a {@link StatusException} with additional
108+
* metadata and the root exception thrown.
109+
*
110+
* <p>The returned {@link StatusException} will wrap a {@link Status} whose code and description
111+
* are set from the code and message in {@code statusProto}. {@code statusProto} will be
112+
* serialized and added to {@code metadata}. {@code metadata} will be set as the metadata of the
113+
* returned {@link StatusException}. The {@link Throwable} is the exception that is set as the
114+
* {@code cause} of the returned {@link StatusException}.
115+
*
116+
* @throws IllegalArgumentException if the value of {@code statusProto.getCode()} is not a valid
117+
* gRPC status code.
118+
* @since 1.3.0
119+
*/
120+
public static StatusException toStatusException(
121+
com.google.rpc.Status statusProto, Metadata metadata, Throwable cause) {
122+
return toStatus(statusProto).withCause(cause).asException(toMetadata(statusProto, metadata));
123+
}
124+
106125
private static Status toStatus(com.google.rpc.Status statusProto) {
107126
Status status = Status.fromCodeValue(statusProto.getCode());
108127
checkArgument(status.getCode().value() == statusProto.getCode(), "invalid status code");

protobuf/src/test/java/io/grpc/protobuf/StatusProtoTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,15 @@ public void fromThrowable_shouldReturnNullIfNoEmbeddedStatus() {
176176
assertNull(StatusProto.fromThrowable(nestedSe));
177177
}
178178

179+
@Test
180+
public void toStatusExceptionWithMetadataAndCause_shouldCaptureCause() {
181+
StatusException se = StatusProto.toStatusException(STATUS_PROTO, new Metadata(),
182+
new RuntimeException("This is a test exception."));
183+
184+
assertNotNull(se.getCause());
185+
assertEquals(se.getCause().getMessage(), "This is a test exception.");
186+
}
187+
179188
private static final Metadata.Key<String> METADATA_KEY =
180189
Metadata.Key.of("test-metadata", Metadata.ASCII_STRING_MARSHALLER);
181190
private static final String METADATA_VALUE = "test metadata value";

0 commit comments

Comments
 (0)