1

I use Retrofit 2:

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'

I've added okhttp3.logging.HttpLoggingInterceptor for logging responses. And I see my logs:

D/OkHttp: <-- 400 Bad Request http://myurl.com/api/ (616ms)
D/OkHttp: Date: Fri, 19 Feb 2016 07:59:50 GMT
D/OkHttp: Server: Apache/2.4.12
D/OkHttp: X-Powered-By: PHP/5.4.45
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: Connection: close
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: OkHttp-Sent-Millis: 1455868788858
D/OkHttp: OkHttp-Received-Millis: 1455868789211
D/OkHttp: {"error_message":"Validation error"}
D/OkHttp: <-- END HTTP (87-byte body)

How can I get error body string from response? In my example it is json string - {"error_message":"Validation error"}

I've tried this way:

import retrofit2.Response;

Reader charStream = response.raw().body().charStream();
BufferedReader in = new BufferedReader(charStream);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
    sb.append(line);
}

But I've get IllegalStateException on this line:

Reader charStream = response.raw().body().charStream();

FATAL EXCEPTION: main
java.lang.IllegalStateException: Cannot read raw response body of a converted body.
retrofit2.OkHttpCall$NoContentResponseBody.source(OkHttpCall.java:257)
at okhttp3.ResponseBody.byteStream(ResponseBody.java:69)
at okhttp3.ResponseBody.charStream(ResponseBody.java:100)
at com.myapp.delegate.retrofit.ApiDelegateRetrofit.parseError(ApiDelegateRetrofit.java:146)

EDIT:

I've resolved it for beta-4 (according to https://stackoverflow.com/a/32896077/1225669):

if (response != null && response.errorBody() != null) {
    Converter<ResponseBody, ErrorData> errorConverter = retrofit.responseBodyConverter(ErrorData.class, new Annotation[0]);
    try {
        ErrorData error = errorConverter.convert(response.errorBody());
        return error;
    } catch (IOException e) {
        //
    }
}
Community
  • 1
  • 1
valerybodak
  • 4,195
  • 2
  • 42
  • 53

2 Answers2

2

Probably you should use response.errorBody() instead of response.raw().body(). Here is more detailed explanation of Retrofit 2 erro handling Retrofit 2.0 how to get deserialised error response.body.

Community
  • 1
  • 1
Yev Kanivets
  • 1,780
  • 3
  • 22
  • 38
  • Thank you. http://stackoverflow.com/a/32896077/1225669. I've modified example of beta-3 to beta-4. Please see my modified question. – valerybodak Feb 19 '16 at 09:04
1

try this

response.errorBody();

or

response.message();

TomDuan
  • 116
  • 1
  • 1
  • 7