Issue
I want to handle error in Retrofit 2.0
Got e.g. code=404
and body=null
, but errorBody()
contains data in ErrorModel
(Boolean status
and String info
).
This is errorBody().content
: [text=\n{"status":false,"info":"Provided email doesn't exist."}]
.
How can I get this data?
Thank for helping me!
This is my code for Retrofit request:
ResetPasswordApi.Factory.getInstance().resetPassword(loginEditText.getText().toString())
.enqueue(new Callback<StatusInfoModel>() {
@Override
public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
if (response.isSuccessful()) {
showToast(getApplicationContext(), getString(R.string.new_password_sent));
} else {
showToast(getApplicationContext(), getString(R.string.email_not_exist));
}
}
@Override
public void onFailure(Call<StatusInfoModel> call, Throwable t) {
showToast(getApplicationContext(), "Something went wrong...");
}
});
Solution
If you want to get data when error response comes (typically a response code except 200) you can do it like that in your onResponse()
method:
if (response.code() == 404) {
Gson gson = new GsonBuilder().create();
YourErrorPojo pojo = new YourErrorPojo();
try {
pojo = gson.fromJson(response.errorBody().string(), YourErrorPojo.class);
Toast.makeText(context, pojo.getInfo(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// handle failure at error parse
}
}
When generating YourErrorPojo.class
do following steps :
Go to Json Schema 2 Pojo
Paste your example
Json
, and select source type Json , annotation GsonYour example
Json
is :{"status":false,"info":"Provided email doesn't exist."}
Click Preview and it will generate your
Pojo
class for you.
Add this to your build.gradle
: compile 'com.google.code.gson:gson:2.7'
I used Gson
in this solution but you can get your Json
string using: response.errorBody().string()
Answered By - Yasin Kaçmaz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.