How to get response body to retrofit exception?

随声附和 提交于 2019-12-02 17:54:53

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);
}

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);
}

Your server should return 4xx HTTP error code to get this working.

When your server returns HTTP 200 this mean successful response and it will be processed with onSuccess branch. Likely your object which you pass to Callback<Object> should be ready to handle both success and error result.

To make sure this is the case you can check if RetrofitError is actually a JsonParseException by adding next snippet:

public void failure(RetrofitError error) {
    Log.v(TAG, error.getMessage());
};

you need use getErrorStream() for this.

If the HTTP response indicates that an error occurred, getInputStream() will throw an IOException. Use getErrorStream() to read the error response. The headers can be read in the normal way using getHeaderFields().

Ref: github issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!