Skip to content

Commit 6913db5

Browse files
authored
feat: update ErrorDetails to allow unpacking arbitrary messages (#3073)
Because the google.rpc.Status.details is a google.protobuf.Any, it can contain any message. ErrorDetails conveniently unpacks the standard status message types from google/rpc/error_details.proto but some services provide their own error details types. This new method allows unpacking those custom messages without deserializing the entire google.rpc.Status another time.
1 parent 7a26115 commit 6913db5

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

gax-java/gax/src/main/java/com/google/api/gax/rpc/ErrorDetails.java

+9
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,15 @@ public LocalizedMessage getLocalizedMessage() {
126126
return unpack(LocalizedMessage.class);
127127
}
128128

129+
/**
130+
* Attempt to unpack a non-default error message type {@code T}. The first occurrence of a {@code
131+
* T} is returned, null otherwise.
132+
*/
133+
@Nullable
134+
public <T extends Message> T getMessage(Class<T> messageClass) {
135+
return unpack(messageClass);
136+
}
137+
129138
/** This is a list of raw/unparsed error messages that returns from server. */
130139
@Nullable
131140
abstract List<Any> getRawErrorMessages();

gax-java/gax/src/test/java/com/google/api/gax/rpc/ErrorDetailsTest.java

+10-1
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,9 @@ class ErrorDetailsTest {
121121
private static final LocalizedMessage LOCALIZED_MESSAGE =
122122
LocalizedMessage.newBuilder().setLocale("en").setMessage("nothing").build();
123123

124+
private static final Duration DURATION_MESSAGE =
125+
Duration.newBuilder().setSeconds(12345).setNanos(54321).build();
126+
124127
ErrorDetails errorDetails;
125128

126129
@BeforeEach
@@ -136,7 +139,8 @@ void setUp() throws Exception {
136139
Any.pack(REQUEST_INFO),
137140
Any.pack(RESOURCE_INFO),
138141
Any.pack(HELP),
139-
Any.pack(LOCALIZED_MESSAGE));
142+
Any.pack(LOCALIZED_MESSAGE),
143+
Any.pack(DURATION_MESSAGE));
140144

141145
errorDetails = ErrorDetails.builder().setRawErrorMessages(rawErrorMessages).build();
142146
}
@@ -228,4 +232,9 @@ void help_shouldUnpackHelpProtoMessage() {
228232
void localizedMessage_shouldUnpackLocalizedMessageProtoMessage() {
229233
Truth.assertThat(errorDetails.getHelp()).isEqualTo(HELP);
230234
}
235+
236+
@Test
237+
void getMessage_duration_shouldUnpackDurationProtoMessage() {
238+
Truth.assertThat(errorDetails.getMessage(Duration.class)).isEqualTo(DURATION_MESSAGE);
239+
}
231240
}

0 commit comments

Comments
 (0)