정성민
정성민

Reputation: 43

retrofit2 get responseBody in onFailure()

When I fail to parse the json from the server, I try to collect the situation. I can see what the server gave me using the class that implements the Interceptor.(LoggingInterceptor) However, I do not seem to be able to get the value in 'onFailure()', a situation where I need to collect errors. Because it only provides 'Call' and 'Throwable'. How do I get raw data from the server in 'onFailure()'?

Below is my code.

LoggingInterceptor

public class LoggingInterceptor implements Interceptor {

//로그에 쓰일 tag
private static final String TAG = CalyApplication.class.getSimpleName() + "/" + LoggingInterceptor.class.getSimpleName();

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    String responseString = new String(response.body().bytes());

    //yes, I can see response in here. but I need it in 'onFailure()'.
    Logger.i(TAG, "code : " + response.code() + "\n" + responseString);


    return  response.newBuilder()
            .body(ResponseBody.create(response.body().contentType(), responseString))
            .build();
    }

}

Actrivity

void fetchData(){

    ApiClient.getService().test(
            "test"
    ).enqueue(new Callback<BasicResponse>() {
        @Override
        public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
            BasicResponse body = response.body();
            switch (response.code()){
                case 200:
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailure(Call<BasicResponse> call, Throwable t) {
            //I want get Response object in here!
            //but it only provides Call&Throwable
        }
    });
}

Thanks!

Upvotes: 4

Views: 8972

Answers (1)

art
art

Reputation: 115

If you get a 4xx or 5xx (error)status code then the onResponse is called, not the onFailure. You get a response body(2xx) or error body accordingly only if the call was successful. So in onResponse you should have the following structure:

if (response.isSuccessful()) {
   // Get response body
} else if (response.errorBody() != null) {
   // Get response errorBody 
   String errorBody = response.errorBody().string();
}

Edit: More info about how to retrieve the errorBody can be found here.

Upvotes: 1

Related Questions