Skip to content

Commit 5c9b492

Browse files
rtadepalliejona86
andauthoredApr 25, 2024··
Add StatusProto.toStatusException overload to accept Throwable (#11083)
* Add `StatusProto.toStatusException` overload to accept `Throwable` --------- Co-authored-by: Eric Anderson <ejona@google.com>
1 parent e036b1b commit 5c9b492

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
 

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

+19
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. The exception isn't propagated over the wire.
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

+8
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,14 @@ public void fromThrowable_shouldReturnNullIfNoEmbeddedStatus() {
176176
assertNull(StatusProto.fromThrowable(nestedSe));
177177
}
178178

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

0 commit comments

Comments
 (0)
Please sign in to comment.