Retrofit 2.0 how to get deserialised error response.body Retrofit 2.0 how to get deserialised error response.body java java

Retrofit 2.0 how to get deserialised error response.body


I currently use a very easy implementation, which does not require to use converters or special classes. The code I use is the following:

public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {    DialogHelper.dismiss();    if (response.isSuccessful()) {        // Do your success stuff...    } else {        try {            JSONObject jObjError = new JSONObject(response.errorBody().string());            Toast.makeText(getContext(), jObjError.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();        } catch (Exception e) {            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();        }    }}


ErrorResponse is your custom response object

Kotlin

val gson = Gson()val type = object : TypeToken<ErrorResponse>() {}.typevar errorResponse: ErrorResponse? = gson.fromJson(response.errorBody()!!.charStream(), type)

Java

Gson gson = new Gson();Type type = new TypeToken<ErrorResponse>() {}.getType();ErrorResponse errorResponse = gson.fromJson(response.errorBody.charStream(),type);


I solved it by:

 if(!response.isSuccessful()){       Gson gson = new Gson();       MyErrorMessage message=gson.fromJson(response.errorBody().charStream(),MyErrorMessage.class);       if(message.getCode()==ErrorCode.DUPLICATE_EMAIL_ID_CODE){                  //DO Error Code specific handling                                }else{                 //DO GENERAL Error Code Specific handling                                       }    }

MyErrorMessage Class:

  public class MyErrorMessage {     private int code;     private String message;     public int getCode() {        return code;     }     public void setCode(int code) {        this.code = code;     }     public String getMessage() {         return message;     }     public void setMessage(String message) {        this.message = message;     }   }