UPDATE:
If you want to use a non-standard class instead of JSONObject below, you can refer to the following:
Custom class:
public class ResponseError { Error error; class Error { int statusCode; String message; } }
Add the following to the WebAPIService interface:
@GET("/api/geterror") Call<ResponseError> getError2();
Then inside MainActivity.java :
Call<ResponseError> responseErrorCall = service.getError2(); responseErrorCall.enqueue(new Callback<ResponseError>() { @Override public void onResponse(Response<ResponseError> response, Retrofit retrofit) { if (response.isSuccess() && response.body() != null){ Log.i(LOG_TAG, response.body().toString()); } else { if (response.errorBody() != null){ RetrofitClient.APIError error = RetrofitClient.ErrorUtils.parseError(response, retrofit); Log.e(LOG_TAG, error.getErrorMessage()); } } } @Override public void onFailure(Throwable t) { Log.e(LOG_TAG, t.toString()); } });
I just checked your RetrofitClient class using my web service. I made a small update for your APIError class as follows (add 2 constructors, they are not actually called):
public APIError(){ this.loginError = new ErrorResponse(); } public APIError(int statusCode, String message) { this.loginError = new ErrorResponse(); this.loginError.statusCode = statusCode; this.loginError.message = message; }
Interface:
public interface WebAPIService { @GET("/api/geterror") Call<JSONObject> getError(); }
MainActivity:
// Retrofit 2.0-beta2 Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL_BASE) .addConverterFactory(GsonConverterFactory.create()) .build(); WebAPIService service = retrofit.create(WebAPIService.class); Call<JSONObject> jsonObjectCall = service.getError(); jsonObjectCall.enqueue(new Callback<JSONObject>() { @Override public void onResponse(Response<JSONObject> response, Retrofit retrofit) { if (response.isSuccess() && response.body() != null){ Log.i(LOG_TAG, response.body().toString()); } else { if (response.errorBody() != null){ RetrofitClient.APIError error = RetrofitClient.ErrorUtils.parseError(response, retrofit); Log.e(LOG_TAG, error.getErrorMessage()); } } } @Override public void onFailure(Throwable t) { Log.e(LOG_TAG, t.toString()); } });
My web service (Asp.Net API):
According to your JSON response data, I used the following code:
[Route("api/geterror")] public HttpResponseMessage GetError() { var detailError = new { message = "Incorrect credentials", statusCode = 401 }; var myError = new { error = detailError }; return Request.CreateResponse(HttpStatusCode.Unauthorized, myError); }
It works! Hope this helps!