Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0 how to get deserialised error response.body

I'm using Retrofit 2.0.0-beta1.

In tests i have an alternate scenario and expect error HTTP 400

I would like to have retrofit.Response<MyError> response but response.body() == null

MyError is not deserialised - i see it only here

response.errorBody().string()

but it doesn't give me MyError as object

like image 670
Piotr Boho Avatar asked Oct 11 '22 10:10

Piotr Boho


2 Answers

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

A point to note here is that response.errorBody().string() will return the correct value only once. If you call it again, it will return an empty string. So in case you want to reuse it, store the value in a variable with the first call.

There is a way to get the error body string from the response without making it empty on the next call, by rolling your own implementation of toString() that does not update the errorBody Buffer's read-pointer. See this answer for more info.

like image 198
Saif Bechan Avatar answered Oct 18 '22 21:10

Saif Bechan


ErrorResponse is your custom response object

Kotlin

val gson = Gson()
val type = object : TypeToken<ErrorResponse>() {}.type
var 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);
like image 83
Shahab Rauf Avatar answered Oct 18 '22 21:10

Shahab Rauf