Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response body to retrofit exception?

I am trying to connect to rest service via retrofit in android application. I am getting responses. But when there is some error response from the service, conversion exception occurs and now I want to do some actions based on the response body. But I am getting response body as NULL. But retrofit log has a error message. Why is this happening.

D/Reftofit log(24856): OkHttp-Received-Millis: 1397527055676 D/Reftofit log(24856): OkHttp-Response-Source: NETWORK 200 D/Reftofit log(24856): OkHttp-Sent-Millis: 1397527055492 D/Reftofit log(24856): Server: Apache/2.2.22 (Ubuntu) D/Reftofit log(24856): X-Powered-By: PHP/5.3.10-1ubuntu3.10 D/Reftofit log(24856): {"result":"Invalid Token ID"} 

Code:

public void failure(RetrofitError retrofitError) {     String response = null;     TokenError tokenError = (TokenError) retrofitError.getBodyAs(TokenError.class);     response = tokenError.getErrorDetails();     Log.e(TAG, response);     if (response != null && response.contains("Invalid Token ID")) {         GroupDataProvider.getInstance().onFailure();     }  } 

Here I am getting tokenError as null. I don't know why? Do I need to set something with rest adapter so that the response will be passed to retrofit error object.

like image 912
Satya Avatar asked Apr 15 '14 02:04

Satya


People also ask

How do I get error response in retrofit?

you can simply use "response. message(). toString()" which will give the same error string in a more readable format.

How do you get a response body from OkHttp?

OkHttp Response To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object.


2 Answers

Try this code:

@Override public void failure(RetrofitError error) {     String json =  new String(((TypedByteArray)error.getResponse().getBody()).getBytes());     Log.v("failure", json.toString()); } 

with Retrofit 2.0

@Override public void onFailure(Call<Example> call, Throwable t) {     String message = t.getMessage();     Log.d("failure", message); } 
like image 56
Cabezas Avatar answered Sep 23 '22 00:09

Cabezas


if error in String format:

public Sring getErrorBodyAsString(RetrofitError error) {           return (String) error.getBodyAs(String.class) } 

if you need custom object:

class ErrorResponse {    @SerializedName("error")    int errorCode;     @SerializedName("msg")    String msg; }  public T getErrorBody(RetrofitError error, Class<T> clazz) {           return (T) error.getBodyAs(clazz); } 
like image 36
Victor Ponomarenko Avatar answered Sep 20 '22 00:09

Victor Ponomarenko