twitter-api-java-sdk icon indicating copy to clipboard operation
twitter-api-java-sdk copied to clipboard

Unmanaged JsonSyntaxException on TweetsApi

Open mmariuzzo opened this issue 2 years ago • 0 comments

In TweetsApi all methods xxxxWithHttpInfo doesn't manage Json exception.

For example, to have recent tweets, the flow goes into tweetsRecentSearchWithHttpInfo that has this code (some parts omitted to help reading)

    private ApiResponse<Get2TweetsSearchRecentResponse> tweetsRecentSearchWithHttpInfo(......) throws ApiException {
        okhttp3.Call localVarCall = tweetsRecentSearchValidateBeforeCall(.....);
        try {
            Type localVarReturnType = new TypeToken<Get2TweetsSearchRecentResponse>(){}.getType();
            return localVarApiClient.execute(localVarCall, localVarReturnType);
        } catch (ApiException e) {
            e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<com.twitter.clientlib.model.ProblemOrError>(){}.getType()));
            throw e;
        }
    }

For some calls I receive this error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Not a JSON Object: "<!DOCTYPE"
    at com.google.gson.Gson.fromJson(Gson.java:1003)
    at com.google.gson.Gson.fromJson(Gson.java:956)
    at com.google.gson.Gson.fromJson(Gson.java:905)
    at com.twitter.clientlib.api.TweetsApi.tweetsRecentSearchWithHttpInfo(TweetsApi.java:5140)
    at com.twitter.clientlib.api.TweetsApi.access$7300(TweetsApi.java:89)
    at com.twitter.clientlib.api.TweetsApi$APItweetsRecentSearchRequest.execute(TweetsApi.java:5362)
    ......
 Caused by: java.lang.IllegalStateException: Not a JSON Object: "<!DOCTYPE"
    at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:91)
    at com.twitter.clientlib.model.ProblemOrError$CustomTypeAdapterFactory$1.read(ProblemOrError.java:114)
    at com.twitter.clientlib.model.ProblemOrError$CustomTypeAdapterFactory$1.read(ProblemOrError.java:86)
    at com.google.gson.TypeAdapter$1.read(TypeAdapter.java:199

as you see in the catch part the setErrorObject assumes the response body is a valid JSON. But it isn't

Expected behavior

The setErrorObject part is surrounded by another try...catch so the real ApiException with headers and body will be accessible by the caller class

Actual behavior

JsonSyntaxException completely hide the original exception

Steps to reproduce the behavior

IMHO this is a 'design' bug. It happens randomly and without the original exception I'm unable to identify the cause

mmariuzzo avatar Mar 08 '23 09:03 mmariuzzo