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?
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With