square / retrofit

A type-safe HTTP client for Android and the JVM
https://square.github.io/retrofit/
Apache License 2.0
43.11k stars 7.3k forks source link

get responseBody in onFailure #2309

Closed JSpiner closed 7 years ago

JSpiner commented 7 years ago

What kind of issue is this?

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!

JakeWharton commented 7 years ago

This issue tracker is not the place for questions. If you want to ask how to do something, or to understand why something isn't working the way you expect it to, use Stack Overflow. https://stackoverflow.com/questions/tagged/retrofit