Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in synchronous call by Retrofit

I'm trying to figure out the right way to do error handling in Retrofit synchronous calls. I know for asynchronous calls, Retrofit has a callback for failure case. But how should I handle error for synchronous call? My guess is wrapping the call with a try block and handle RetrofitError exception in catch block.

like image 704
Fei Qu Avatar asked May 18 '15 18:05

Fei Qu


People also ask

What is callback in retrofit?

public interface Callback<T> Communicates responses from a server or offline requests. One and only one method will be invoked in response to a given request. Callback methods are executed using the Retrofit callback executor.

How does retrofit work?

Retrofit is used to perform the following tasks: It manages the process of receiving, sending, and creating HTTP requests and responses. It alternates IP addresses if there is a connection to a web service failure. It caches responses to avoid sending duplicate requests.


2 Answers

Your guess seems correct, using synchronous calls Retrofit is made to throw a RetrofitError representing the error: Reference. Note that the throw IllegalStateException in handleError shouldn't happen in the case of a synchronous call.

Edit: It appears Retrofit is slowly moving on to the 2.0 release, if you plan on using Retrofit 2.0, I recommend reading the documentations to see how it is done in the new version.

Edit pt2: Retrofit has moved to 2.0 release and now if you want to handle errors you no longer have to catch RetrofitErrors but IOException. You can directly have a look at the implementation of execute()

/**
 * Synchronously send the request and return its response.
 *
 * @throws IOException if a problem occurred talking to the server.
 * @throws RuntimeException (and subclasses) if an unexpected error occurs creating the request
 * or decoding the response.
 */
Response<T> execute() throws IOException;

Other references: 1

like image 181
Bhullnatik Avatar answered Sep 22 '22 22:09

Bhullnatik


It's hard to find this. Nobody really talks about the error handling on synchronous calls. But I found something. I'm not entirely sure if the next line should be added (it should definitely be added for custom errors, but this is not the case) I found it here

Foo doFoo() throws RetroFitError;

The synchronous call should be happening inside a try catch clause like this:

try{
    doFoo();
}catch(RetroFitError e){

}

Found here

like image 39
Kevin van Mierlo Avatar answered Sep 18 '22 22:09

Kevin van Mierlo