Retrofit 2 - 获取错误对象 JSON(相同请求的几个 POJO)

Retrofit 2 - get error-object JSON (few POJO for same request)

我有一个简单的请求,比如

  /*LOGIN*/
        @FormUrlEncoded
        @POST("v1/user/login") //your login function in your api
        Call<LoginResponce> login(@Field("identity") String identity,
               @Field("password") String password);

哪个returns LoginResponceobject if http code 200

{"token":"itwbwKay7iUIOgT-GqnYeS_IXdjJi","user_id":17}

或错误 Json,描述确切的错误,如果出现问题

{"status":4,"description":"user provided token expired"}

如何处理响应中的错误状态?

我试过了,但在原始文本中看不到 JSON(不起作用)。而且似乎不是很好的解决方案。

mCallLoginResponse.enqueue(new Callback<LoginResponce>() {
                @Override
                public void onResponse(Response<LoginResponce> response, Retrofit retrofit) {
                    if (response.isSuccess()) {

                        registerWithToken(response.body().getToken());
                    } else { //some error in responce

                        Gson gson = new GsonBuilder().create();
                        ApiError mApiError = gson.fromJson(response.raw().body().toString(), 
ApiError.class); //Exception here - no JSON in String
                            //todo error handling
                        }
                    }

要在有错误代码时访问响应正文,请使用 errorBody() 而不是 body()。此外,ResponseBody 上有一个 string 方法,您应该使用它来代替 toString

Gson gson = new GsonBuilder().create();
try {
    ApiError mApiError = gson.fromJson(response.errorBody().string(),ApiError.class); 
} catch (IOException e) {
    // handle failure to read error
}