Skip to content

Commit

Permalink
feat: update ErrorDetails to allow unpacking arbitrary messages (#3073)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
BenWhitehead authored Jul 29, 2024
1 parent 7a26115 commit 6913db5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,15 @@ public LocalizedMessage getLocalizedMessage() {
return unpack(LocalizedMessage.class);
}

/**
* Attempt to unpack a non-default error message type {@code T}. The first occurrence of a {@code
* T} is returned, null otherwise.
*/
@Nullable
public <T extends Message> T getMessage(Class<T> messageClass) {
return unpack(messageClass);
}

/** This is a list of raw/unparsed error messages that returns from server. */
@Nullable
abstract List<Any> getRawErrorMessages();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ class ErrorDetailsTest {
private static final LocalizedMessage LOCALIZED_MESSAGE =
LocalizedMessage.newBuilder().setLocale("en").setMessage("nothing").build();

private static final Duration DURATION_MESSAGE =
Duration.newBuilder().setSeconds(12345).setNanos(54321).build();

ErrorDetails errorDetails;

@BeforeEach
Expand All @@ -136,7 +139,8 @@ void setUp() throws Exception {
Any.pack(REQUEST_INFO),
Any.pack(RESOURCE_INFO),
Any.pack(HELP),
Any.pack(LOCALIZED_MESSAGE));
Any.pack(LOCALIZED_MESSAGE),
Any.pack(DURATION_MESSAGE));

errorDetails = ErrorDetails.builder().setRawErrorMessages(rawErrorMessages).build();
}
Expand Down Expand Up @@ -228,4 +232,9 @@ void help_shouldUnpackHelpProtoMessage() {
void localizedMessage_shouldUnpackLocalizedMessageProtoMessage() {
Truth.assertThat(errorDetails.getHelp()).isEqualTo(HELP);
}

@Test
void getMessage_duration_shouldUnpackDurationProtoMessage() {
Truth.assertThat(errorDetails.getMessage(Duration.class)).isEqualTo(DURATION_MESSAGE);
}
}

0 comments on commit 6913db5

Please sign in to comment.