Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
import com.google.api.client.http.HttpResponseException;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.ErrorDetails;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.common.collect.ImmutableSet;
import com.google.rpc.Status;
import java.util.Set;
import java.util.concurrent.CancellationException;

Expand All @@ -51,7 +53,17 @@ ApiException create(Throwable throwable) {
StatusCode statusCode = HttpJsonStatusCode.of(e.getStatusCode());
boolean canRetry = retryableCodes.contains(statusCode.getCode());
String message = e.getStatusMessage();
return createApiException(throwable, statusCode, message, canRetry);
Status status = HttpJsonErrorParser.parseStatus(e.getContent());

if (!status.getMessage().isEmpty()) {
message = status.getMessage();
}

ErrorDetails errorDetails =
ErrorDetails.builder().setRawErrorMessages(status.getDetailsList()).build();

return ApiExceptionFactory.createException(
message, throwable, statusCode, canRetry, errorDetails);
} else if (throwable instanceof HttpJsonStatusRuntimeException) {
HttpJsonStatusRuntimeException e = (HttpJsonStatusRuntimeException) throwable;
StatusCode statusCode = HttpJsonStatusCode.of(e.getStatusCode());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,21 @@ static Status parseStatus(String errorJson) {
return Status.getDefaultInstance();
}

// AIP-193 specifies that the 'status' field contains the gRPC status as a string.
// The 'code' field typically contains the HTTP status code, which JsonFormat natively
// maps into the Builder's 'code' field. To ensure the resulting com.google.rpc.Status
// has the correct gRPC integer code, we override it using the 'status' string if present.
if (errorElement.getAsJsonObject().has("status")) {
try {
String statusStr = errorElement.getAsJsonObject().get("status").getAsString();
com.google.rpc.Code rpcCode = com.google.rpc.Code.valueOf(statusStr);
statusBuilder.setCode(rpcCode.getNumber());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems a little hacky to override the response directly. I would rather use the current statusCode as I mentioned in another comment.

If we really need this info, I would suggest returning this info separately. For example, an object that wraps both Status and grpcStatusCode.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left the current statusCode here, thank you!

} catch (IllegalArgumentException | UnsupportedOperationException e) {
// Ignore if the status string doesn't match a known google.rpc.Code enum value,
// or if it isn't a string.
}
}

return statusBuilder.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.api.gax.httpjson;

import static com.google.common.truth.Truth.assertThat;

import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpResponseException;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ErrorDetails;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.Test;

class HttpJsonApiExceptionFactoryTest {

@Test
void testCreate_withAllFieldsPresent() {
String payload =
"{\n"
+ " \"error\": {\n"
+ " \"code\": 7,\n"
+ " \"message\": \"The caller does not have permission\",\n"
+ " \"details\": [\n"
+ " {\n"
+ " \"@type\": \"type.googleapis.com/google.rpc.ErrorInfo\",\n"
+ " \"reason\": \"SERVICE_DISABLED\",\n"
+ " \"domain\": \"googleapis.com\",\n"
+ " \"metadata\": {\n"
+ " \"service\": \"pubsub.googleapis.com\"\n"
+ " }\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";

HttpResponseException exception =
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders())
.setContent(payload)
.build();

HttpJsonApiExceptionFactory factory =
new HttpJsonApiExceptionFactory(ImmutableSet.of(Code.UNAVAILABLE));
ApiException apiException = factory.create(exception);

// The status code should be derived from the JSON code (7), ignoring HTTP code (403).
assertThat(apiException.getStatusCode().getCode()).isEqualTo(Code.PERMISSION_DENIED);
assertThat(apiException.isRetryable()).isFalse();
// The message should be overridden by the JSON message
assertThat(apiException.getMessage()).contains("The caller does not have permission");

ErrorDetails details = apiException.getErrorDetails();
assertThat(details).isNotNull();
assertThat(details.getErrorInfo()).isNotNull();
assertThat(details.getErrorInfo().getReason()).isEqualTo("SERVICE_DISABLED");
assertThat(details.getErrorInfo().getDomain()).isEqualTo("googleapis.com");
assertThat(details.getErrorInfo().getMetadataMap().get("service"))
.isEqualTo("pubsub.googleapis.com");
}

@Test
void testCreate_withOkStatusNoMessageNoDetails() {
String payload = "{\n \"error\": {\n \"code\": 0\n }\n}";

HttpResponseException exception =
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders())
.setContent(payload)
.build();

HttpJsonApiExceptionFactory factory =
new HttpJsonApiExceptionFactory(ImmutableSet.of(Code.UNAVAILABLE));
ApiException apiException = factory.create(exception);

// Because code is 0 (OK), it falls back to the HTTP status code (403 -> PERMISSION_DENIED).
assertThat(apiException.getStatusCode().getCode()).isEqualTo(Code.PERMISSION_DENIED);
assertThat(apiException.isRetryable()).isFalse();
// Because there is no message in the payload, it falls back to the HTTP status message.
assertThat(apiException.getMessage()).contains("Forbidden");
// Details are unconditionally built, but empty.
assertThat(apiException.getErrorDetails()).isNotNull();
assertThat(apiException.getErrorDetails().getErrorInfo()).isNull();
}

@Test
void testCreate_withMessageOverridesHttpStatusMessage() {
String payload =
"{\n"
+ " \"error\": {\n"
+ " \"message\": \"Custom detailed error message from server\"\n"
+ " }\n"
+ "}";

// Transport layer returned generic "Bad Request" phrase
HttpResponseException exception =
new HttpResponseException.Builder(400, "Bad Request", new HttpHeaders())
.setContent(payload)
.build();

HttpJsonApiExceptionFactory factory =
new HttpJsonApiExceptionFactory(ImmutableSet.of(Code.UNAVAILABLE));
ApiException apiException = factory.create(exception);

assertThat(apiException.getMessage()).contains("Custom detailed error message from server");
assertThat(apiException.getMessage()).doesNotContain("Bad Request");
}

@Test
void testCreate_withoutErrorDetails() {
HttpResponseException exception =
new HttpResponseException.Builder(503, "Service Unavailable", new HttpHeaders())
.setContent("plain text error")
.build();

HttpJsonApiExceptionFactory factory =
new HttpJsonApiExceptionFactory(ImmutableSet.of(Code.UNAVAILABLE));
ApiException apiException = factory.create(exception);

assertThat(apiException.getStatusCode().getCode()).isEqualTo(Code.UNAVAILABLE);
assertThat(apiException.isRetryable()).isTrue();
// Plain text error parsing will still generate an empty ErrorDetails
assertThat(apiException.getErrorDetails()).isNotNull();
assertThat(apiException.getErrorDetails().getErrorInfo()).isNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ void parseStatus_success() {

com.google.rpc.Status status = HttpJsonErrorParser.parseStatus(payload);
assertThat(status).isNotNull();
assertThat(status.getCode()).isEqualTo(401);
assertThat(status.getCode()).isEqualTo(16);
assertThat(status.getMessage())
.isEqualTo("Request is missing required authentication credential.");

Expand Down Expand Up @@ -135,4 +135,40 @@ void parseStatus_arrayInError() {
assertThat(HttpJsonErrorParser.parseStatus(payload))
.isEqualTo(com.google.rpc.Status.getDefaultInstance());
}

@Test
void parseStatus_withHttpCodeAndGrpcStatusString() {
// AIP-193 standard JSON mapping typically includes the HTTP code in "code"
// and the gRPC status string in "status". Let's verify what JsonFormat actually extracts
// to the `com.google.rpc.Status` proto when both are present.
String payload =
"{\n"
+ " \"error\": {\n"
+ " \"code\": 403,\n"
+ " \"status\": \"PERMISSION_DENIED\",\n"
+ " \"message\": \"The caller does not have permission\"\n"
+ " }\n"
+ "}";

com.google.rpc.Status status = HttpJsonErrorParser.parseStatus(payload);

// In Protobuf, com.google.rpc.Status ONLY has `int32 code = 1;` and `string message = 2;`
// It does NOT have a `status` field. Because we use `.ignoringUnknownFields()` in the parser,
// the "status": "PERMISSION_DENIED" string is completely thrown away natively.
// However, our parser manually intercepts the 'status' string to override the gRPC integer.
// So we expect 7 (PERMISSION_DENIED), not 403!
assertThat(status.getCode()).isEqualTo(7);
assertThat(status.getMessage()).isEqualTo("The caller does not have permission");
}

@Test
void parseStatus_withOnlyStatusString() {
String payload = "{\n" + " \"error\": {\n" + " \"status\": \"NOT_FOUND\"\n" + " }\n" + "}";

com.google.rpc.Status status = HttpJsonErrorParser.parseStatus(payload);

// Because "code" is missing, JsonFormat sets it to 0 (OK). But our manual override
// sees "status": "NOT_FOUND" and correctly maps it to 5.
assertThat(status.getCode()).isEqualTo(5);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,13 @@ public AbortedException(
Throwable cause, StatusCode statusCode, boolean retryable, ErrorDetails errorDetails) {
super(cause, statusCode, retryable, errorDetails);
}

public AbortedException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
super(message, cause, statusCode, retryable, errorDetails);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,13 @@ public AlreadyExistsException(
Throwable cause, StatusCode statusCode, boolean retryable, ErrorDetails errorDetails) {
super(cause, statusCode, retryable, errorDetails);
}

public AlreadyExistsException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
super(message, cause, statusCode, retryable, errorDetails);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ public ApiException(
this.errorDetails = errorDetails;
}

public ApiException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
super(message, cause);
this.statusCode = Preconditions.checkNotNull(statusCode);
this.retryable = retryable;
this.errorDetails = errorDetails;
}

/** Returns whether the failed request can be retried. */
public boolean isRetryable() {
return retryable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,40 +83,49 @@ public static ApiException createException(

public static ApiException createException(
Throwable cause, StatusCode statusCode, boolean retryable, ErrorDetails errorDetails) {
return createException(null, cause, statusCode, retryable, errorDetails);
}

public static ApiException createException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
switch (statusCode.getCode()) {
case CANCELLED:
return new CancelledException(cause, statusCode, retryable, errorDetails);
return new CancelledException(message, cause, statusCode, retryable, errorDetails);
case NOT_FOUND:
return new NotFoundException(cause, statusCode, retryable, errorDetails);
return new NotFoundException(message, cause, statusCode, retryable, errorDetails);
case INVALID_ARGUMENT:
return new InvalidArgumentException(cause, statusCode, retryable, errorDetails);
return new InvalidArgumentException(message, cause, statusCode, retryable, errorDetails);
case DEADLINE_EXCEEDED:
return new DeadlineExceededException(cause, statusCode, retryable, errorDetails);
return new DeadlineExceededException(message, cause, statusCode, retryable, errorDetails);
case ALREADY_EXISTS:
return new AlreadyExistsException(cause, statusCode, retryable, errorDetails);
return new AlreadyExistsException(message, cause, statusCode, retryable, errorDetails);
case PERMISSION_DENIED:
return new PermissionDeniedException(cause, statusCode, retryable, errorDetails);
return new PermissionDeniedException(message, cause, statusCode, retryable, errorDetails);
case RESOURCE_EXHAUSTED:
return new ResourceExhaustedException(cause, statusCode, retryable, errorDetails);
return new ResourceExhaustedException(message, cause, statusCode, retryable, errorDetails);
case FAILED_PRECONDITION:
return new FailedPreconditionException(cause, statusCode, retryable, errorDetails);
return new FailedPreconditionException(message, cause, statusCode, retryable, errorDetails);
case ABORTED:
return new AbortedException(cause, statusCode, retryable, errorDetails);
return new AbortedException(message, cause, statusCode, retryable, errorDetails);
case OUT_OF_RANGE:
return new OutOfRangeException(cause, statusCode, retryable, errorDetails);
return new OutOfRangeException(message, cause, statusCode, retryable, errorDetails);
case UNIMPLEMENTED:
return new UnimplementedException(cause, statusCode, retryable, errorDetails);
return new UnimplementedException(message, cause, statusCode, retryable, errorDetails);
case INTERNAL:
return new InternalException(cause, statusCode, retryable, errorDetails);
return new InternalException(message, cause, statusCode, retryable, errorDetails);
case UNAVAILABLE:
return new UnavailableException(cause, statusCode, retryable, errorDetails);
return new UnavailableException(message, cause, statusCode, retryable, errorDetails);
case DATA_LOSS:
return new DataLossException(cause, statusCode, retryable, errorDetails);
return new DataLossException(message, cause, statusCode, retryable, errorDetails);
case UNAUTHENTICATED:
return new UnauthenticatedException(cause, statusCode, retryable, errorDetails);
return new UnauthenticatedException(message, cause, statusCode, retryable, errorDetails);
case UNKNOWN: // Fall through.
default:
return new UnknownException(cause, statusCode, retryable, errorDetails);
return new UnknownException(message, cause, statusCode, retryable, errorDetails);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,13 @@ public CancelledException(
Throwable cause, StatusCode statusCode, boolean retryable, ErrorDetails errorDetails) {
super(cause, statusCode, retryable, errorDetails);
}

public CancelledException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
super(message, cause, statusCode, retryable, errorDetails);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,13 @@ public DataLossException(
Throwable cause, StatusCode statusCode, boolean retryable, ErrorDetails errorDetails) {
super(cause, statusCode, retryable, errorDetails);
}

public DataLossException(
String message,
Throwable cause,
StatusCode statusCode,
boolean retryable,
ErrorDetails errorDetails) {
super(message, cause, statusCode, retryable, errorDetails);
}
}
Loading
Loading