Fei Qu
Fei Qu

Reputation: 979

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.

Upvotes: 19

Views: 6212

Answers (2)

Bhullnatik
Bhullnatik

Reputation: 1312

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

Upvotes: 6

Kevin van Mierlo
Kevin van Mierlo

Reputation: 9814

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

Upvotes: 4

Related Questions