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.
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.
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.
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
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
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