Andrej Jurkin
Andrej Jurkin

Reputation: 2256

GSON: expecting a JSON response, but API returns HTML error page on internal errors (500)

I have a Retrofit + Gson setup, which leaks the connection due to

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

The REST API I work with returns a HTML error page instead of a JSON response on internal server errors (500).

Is there a way to handle this case on a client level? Let's say if I receive an error response with status code 500, Retrofit or GSON should not try to deserialise the response.

Upvotes: 0

Views: 850

Answers (1)

nbokmans
nbokmans

Reputation: 5747

If you are using OkHttpClient as your http client for Retrofit you can add an interceptor to the OkHttpClient and if the request returns an error you can do something with it. Example:

public class InternalServerErrorInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            //do whatever you want to do with the response here
        }
        return response;
    }
}

...

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new InternalServerErrorInterceptor())
    .build();

RestAdapter.Builder builder = new RestAdapter.Builder()  
        .setClient(new Ok3Client(client))
        .setEndpoint(API_BASE_URL); //Ok3Client: https://github.com/JakeWharton/retrofit1-okhttp3-client

Upvotes: 1

Related Questions