From 942646f33bb1cfa3c99886bf85a575b342d346a8 Mon Sep 17 00:00:00 2001 From: BenWhitehead Date: Fri, 26 Jul 2024 13:54:10 -0400 Subject: [PATCH] feat: update ErrorDetails to allow unpacking arbitrary messages 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. --- .../java/com/google/api/gax/rpc/ErrorDetails.java | 9 +++++++++ .../java/com/google/api/gax/rpc/ErrorDetailsTest.java | 11 ++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ErrorDetails.java b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ErrorDetails.java index 09c924b59f..45ba427b6e 100644 --- a/gax-java/gax/src/main/java/com/google/api/gax/rpc/ErrorDetails.java +++ b/gax-java/gax/src/main/java/com/google/api/gax/rpc/ErrorDetails.java @@ -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 getMessage(Class messageClass) { + return unpack(messageClass); + } + /** This is a list of raw/unparsed error messages that returns from server. */ @Nullable abstract List getRawErrorMessages(); diff --git a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ErrorDetailsTest.java b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ErrorDetailsTest.java index 36d966804d..90d05e5e3b 100644 --- a/gax-java/gax/src/test/java/com/google/api/gax/rpc/ErrorDetailsTest.java +++ b/gax-java/gax/src/test/java/com/google/api/gax/rpc/ErrorDetailsTest.java @@ -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 @@ -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(); } @@ -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); + } }