Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2: responseBodyConverter converts to null object

I'm using the latest (as of now 2.0.0-beta4) version of Retrofit. When receiving 200 OK code from server, everything is working fine. But I want to deal with not OK responses too, such as code 401. So, I have to get the error response code to figure out exactly what action to do and display appropriate data:

@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
    if (response != null && !response.isSuccess() && response.errorBody() != null) {
        Converter<ResponseBody, APIError> errorConverter = retrofit.responseBodyConverter(APIError.class, new Annotation[0]);
        try {
            APIError error = errorConverter.convert(response.errorBody());
            Toast.makeText(getContext(), "code = " + error.getCode() + ", status = " + error.getStatus(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (null != response) {
        if (response.isSuccess()) {
            LoginResponse loginResponse = response.body();
            Toast.makeText(getContext(), "Successful login: " + loginResponse.getId(), Toast.LENGTH_SHORT).show();
        }
    }
}

APIError.java

public class APIError {
    String name;
    int status;
    String message;
    int statusCode;
    String code;
    String stack;

    public String getName() {
        return name;
    }

    public int getStatus() {
        return status;
    }

    public String getCode() {
        return code;
    }
}

Server's error response

{
  "error": {
    "name": "Error",
    "status": 401,
    "message": "login failed",
    "statusCode": 401,
    "code": "LOGIN_FAILED",
    "stack": "Error: login failed"
  }
}

But errorConverter.convert() returns an object with null values. I've looked similar posts, but it didn't help.

What is wrong with the code?

like image 353
azizbekian Avatar asked Apr 01 '16 07:04

azizbekian


1 Answers

Found the answer in futurestud.io blog comments:

Changed the APIError.java to this:

public class APIError {

    Error error;

    public Error getError() {
        return error;
    }

    public static class Error {

        String name;
        int status;
        String message;
        int statusCode;
        String code;
        String stack;

        public String getName() {
            return name;
        }

        public int getStatus() {
            return status;
        }

        public String getCode() {
            return code;
        }

    }
}
like image 117
azizbekian Avatar answered Oct 14 '22 03:10

azizbekian