My request should get either JSON for POJO or JSON described error(can be invalid request fields, server problems and so on).
But retrofit in subscriber gives me only Throwable. How can I find out is that a network error, what is http code, and get JSON with error?
private class ProjectListSubscriber extends Subscriber<ProjectListResponse> {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
//is that a network? http code? convert json to error POJO?
}
#Override
public void onNext(ProjectListResponse projectListResponse) {
updateProjectList(projectListResponse.getProjectList());
}
}
Since you are using RxJava, onError is called in case of network errors and endpoints related error are part of the Response.
In case of error, check if the throwable is an instance of HttpException
public void onError(Throwable e) {
if (e instanceof HttpException) {
if the check is true, the you have an error in your request. Cast the throwable to HttpException, and access is members. E.g.
((HttpException) e).response().errorBody()
if the check is false then you have a network related error.
Related
I know there are lots of tutorials for OkHttp, but basically all of them do something different in the onResponse method and most don't bother to explain why. Some check for if (response.isSuccessful), some surround it with try/catch, some don't do any of this at all.
This is my example project. What is the proper way to handle the onResponse method?
public class MainActivity extends AppCompatActivity {
private TextView textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = findViewById(R.id.text_view_result);
OkHttpClient client = new OkHttpClient();
String url = "https://reqres.in/api/users?page=2";
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
textViewResult.setText(myResponse);
}
});
}
});
}
}
Update
onResponse of okhttp runs on background thread. So, yes, it's necessary to do MainActivity.this.runOnUiThread(...).
Original answer
onResponse callback already runs on ui thread AFAIK. So, you don't actually need to do MainActivity.this.runOnUiThread(...).
And everyone's onResponse is different because everyone has different needs. Use try/catch if your operations in onResponse might give error and you don't want it to crash.
For some network requests you may need to check if response is successful for other you may not. It all depends on use cases. Do what works for you best.
I'd suggest you surround your code in onResponse in a try/catch block because the user might close the app before the network request is finished. And when you set the textview text in onResponse it will crash because the activity and that textview doesn't exist anymore.
Adding to the answer from rafid. There are basically three cases you want to check.
response.isSuccessful() => status code between 200 and 300
response.code() => to manually check after response is not successful
onFailure() => Network error or parsing error etc.
Ideally your callback would handle those cases something like
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// network error or parsing error
}
#Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
// do stuff all good
} else {
// handle different cases for different status codes or dump them all here
}
}
});
The reason you need a try-catch is because OkHttp is trying to parse the response. This is the case for example for response.errorBody().string();. Another case would be if your Callback<T> has actually a type parameter. Again OkHttp will try to parse the response to that type. If it fails it will result in a callback onto the onFailure method.
I think you need to make sure you know the legal response from the request, like an json or File. if it's just a json, use like below:
#Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
if (response.isSuccessful() && !TextUtils.isEmpty(myResponse)) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
textViewResult.setText(myResponse);
}
});
}
}
Edit: To be more clear.
Callback is running in mainThread so there is no need to call runOnUiThread.
If response is not successful you can try to parse error body as below. If response is successful you can parse with Gson as i show.
String message = "";
if (response.errorBody() != null) {
try {
message = response.errorBody().string();
} catch (IOException ignored) {
Log.e("OkHttp IOException", "error while parsing response");
}
Log.d("Error Message", message);
}
I recommend you to use Gson Library. First you should create your pojo class. You can use http://www.jsonschema2pojo.org/ to create your pojo class. Then you can parse body like below
Gson gson = new Gson();
MyPojo myPojo = gson.fromJson(response.body().charStream(), MyPojo.class);
I am implementation for Retrofit on api call using images-upload base64Encode string. it is sending data perfect but Retrofit return response Internal Server Error 500 and i am sending request type is Body custom class. Plz help me what i do.
#Headers("Accept:application/json")
#POST(RestClient.postRegister)
Call<RegisterResp> getRegisterResponse(#Body RequestRegisterVo requestRegisterVo);
Call<RegisterResp> call = MyApplication.getRestClient().getApplicationServices().getRegisterResponse(requestRegisterVo);
call.enqueue(new Callback<RegisterResp>() {
#Override
public void onResponse(Call<RegisterResp> call, Response<RegisterResp> response) {
if (Other.isValidResp(response)) {
// success Log.i(TAG,"Register successfully");
} else {
hideDialog();
}
}
#Override
public void onFailure(Call<RegisterResp> call, Throwable t) {
hideDialog();
showToast(t.getMessage());
}
});
The same issue I had to face it, I got a solution in my case-
there is parameter issue, I was sending parameters in String and at the backend, they required Integer parameters.
You also checkout may be there is the issue with parameters or second reason is the URL issue so check it URL also.
I'm using Retrofit 2.0 along with RxJava and I need to make a custom error handler so that I can get the HTTP error code. This is the example that I get, but it won't work on Retrofit 2.0, since RetrofitError is removed.
#Override
public void onError(Throwable e) {
if (e instanceof RetrofitError) {
if (((RetrofitError) e).isNetworkError()) {
//handle network error
} else {
//handle error message from server
}
}
}
Is there any way that I can do this? Thanks.
I'm sorry that I didn't read the documentation carefully, so I just find a simple answer that works
#Override
public void onError(Throwable e) {
HttpException exception = (HttpException) e;
Toast.makeText(getApplicationContext(), exception.code() + "", Toast.LENGTH_SHORT).show();
}
I'm new in Robospice and I'm having a problem in handling error request. Is there a way that I can access the Response body from an error request in onRequestFailure method? If not, how you guys do it?
private class RequestListener implements RequestListener<Object> {
#Override
public void onRequestFailure(SpiceException e) {
}
#Override
public void onRequestSuccess(Object response) {
}
}
There's a suggestion that I should do the error checking inside the Spice Request. Any suggestion guys?
#Override
public SubscriptionsContainer loadDataFromNetwork() {
ResponseEntity<SubscriptionsContainer> response = null;
try {
response = getRestTemplate().exchange(/*your request data*/);
} catch (HttpClientErrorException e) {
String responsebody = e.getResponseBodyAsString();
}
}
If you throw any exception from loadDataFromNetwork(), it will be wrapped as SpiceException and passed to onRequestFailure() as its argument.
Therefore, you should check your ResponseEntity<T> for the conditions you expect and throw an exception in case those are not fulfilled.
If, on another hand, your RestTemplate.exchange call throws an exception, you could also handle it (as in your example) or let it be thrown (so it will be reported with onRequestFailure() on the main thread).
I am using Retrofit for both asynchronous and synchronous api calls.
For both I have a custom error handler defined to handle unauthorised responses. For the synchronous calls I have declared the custom exception on the interface methods, I surround the interface implementation with a try/catch and it works perfect. I can catch Unauthorised Exceptions.
I have tried the same with asynchronous calls that use a callback and it doesn't work the same. Instead of the catching the Exception in the try/catch, I have to handle it in the failure method of the callback.
Here is the interface method:
#GET("getGardenGnomes")
void getGardenGnomes(#Header("Authorisation") String authorisation, Callback<GardenGnomes> callback) throws UnauthorisedException;
Here is the implementation:
void onClick() {
try {
getGardenGnomes()
} catch (UnauthorisedException exception) {
// .... handle the exception ....
}
}
void getGardenGnomes() throws UnauthorisedException {
// .... get client etc etc ....
client.getGardenGnomes(authorisation, new Callback<GardenGnomes>() {
#Override
public void success(GardenGnomes gardenGnomes, Response response) {
// .... do something ....
}
#Override
public void failure(RetrofitError error) {
// .... handle error ....
}
}
);
}
The question is:
Should I just handle the exception in the failure(RetrofitError error) method of the Callback and don't declare throws UnauthorisedException on the interface method of asynchronous calls?
Or what is the best way to implement this?
The anwser is yes. Using Retrofit interfaces you don't declare which exception is thrown from the implementation on the interface. RetrofitError is a RuntimeException therefore unchecked. It's expected that a RetrofitError will be thrown on failures from the Retrofit implementation and you're responsible for handling it accordingly. Using synchronous method you simply use the try/catch as you mentioned. Using the asynchronous method you handle it in the failure callback method.
public void methodToHandleRetrofitError(RetrofitError error) {
// handle the error
}
// Synchronous
try {
client.getGardenGnomes(authorization)
} catch (RetrofitError e) {
methodToHandleRetrofitError(e);
}
// Asynchronous
client.getGardenGnomes(authorisation, new Callback<GardenGnomes>() {
#Override
public void success(GardenGnomes gardenGnomes, Response response) {
// .... do something ....
}
#Override
public void failure(RetrofitError error) {
methodToHandleRetrofitError(error);
}
}
);
Hope this clarifies things for ya!