Thursday, 9 May 2019

Access Raw Response After Conversion

I've a backend that returns 200 HTTP code even if the request had errors:

{
    "error": {
        "message": "Generic error",
        "code": 13000
    }
}

Now, how can I access raw response body, after using:

.addConverterFactory(GsonConverterFactory.create(gson))

I've tried:

response.raw().body().string()

But I get:

java.lang.IllegalStateException: Cannot read raw response body of a converted body.

I've implemented a generic APICallback class, that should "block" the success and fire an APIError event:

abstract class APICallback<T> implements Callback<T> {

    abstract void onSuccess(Call<T> call, T result);

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.body() != null) {

            if (response.body() instanceof APIError) {
                // this is not working
            } else {
                onSuccess(call, response.body());
            }
        } else {
            apiError = new APIError("Unknown error");
            bus.post(new APIErrorEvent(apiError));
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        String message = t.getLocalizedMessage() != null ? t.getLocalizedMessage() : "Unknown error";
        apiError = new APIError(message);
        bus.post(new APIErrorEvent(apiError, source));
    }
}

I'd like to mantain the "auto-converter" capability...many thanks in advance.



from Access Raw Response After Conversion

No comments:

Post a Comment