Skip to content

Commit

Permalink
Make GsonGraphQLResponseFactory.buildResponse throw on empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
manueliglesias committed Jan 4, 2023
1 parent e40b03c commit 8e88676
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.amplifyframework.api.graphql.GraphQLRequest;
import com.amplifyframework.api.graphql.GraphQLResponse;
import com.amplifyframework.api.graphql.PaginatedResult;
import com.amplifyframework.util.Empty;
import com.amplifyframework.util.GsonFactory;
import com.amplifyframework.util.TypeMaker;

Expand Down Expand Up @@ -56,6 +57,18 @@ final class GsonGraphQLResponseFactory implements GraphQLResponse.Factory {
@Override
public <T> GraphQLResponse<T> buildResponse(GraphQLRequest<T> request, String responseJson)
throws ApiException {

// On empty strings, Gson returns null instead of throwing JsonSyntaxException. See:
// https://github.com/google/gson/issues/457
// https://github.com/google/gson/issues/1697
if (Empty.check(responseJson)) {
throw new ApiException(
"Amplify encountered an error while deserializing an object.",
new JsonParseException("Empty response."),
AmplifyException.TODO_RECOVERY_SUGGESTION
);
}

Type responseType = TypeMaker.getParameterizedType(GraphQLResponse.class, request.getResponseType());
try {
Gson responseGson = gson.newBuilder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,26 @@ public void nonJsonResponseThrowsApiException() throws ApiException {
});
}

/**
* Validates that an empty response throws an
* ApiException instead of returning a null reference.
* @throws ApiException From API configuration
*/
@Test
public void emptyResponseThrowsApiException() throws ApiException {
// Arrange some empty string from a "server"
final String emptyResponse = "";

// Act! Parse it into a model.
Type responseType = TypeMaker.getParameterizedType(PaginatedResult.class, Todo.class);
GraphQLRequest<PaginatedResult<Todo>> request = buildDummyRequest(responseType);

// Assert that the appropriate exception is thrown
assertThrows(ApiException.class, () -> {
responseFactory.buildResponse(request, emptyResponse);
});
}

/**
* Validates that the converter is able to parse a partial GraphQL
* response into a result. In this case, the result contains some
Expand Down

0 comments on commit 8e88676

Please sign in to comment.