Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling specific errors by sending another request transparently in retrofit

Here's the case I'm trying to handle,

  • If a request is executed, and the response indicates the auth token is expired,
  • send a refresh token request
  • if the refresh token request succeeds, retry the original request

This should be transparent to the calling Activity, Fragment... etc. From the caller's point of view, it's one request, and one response.

I've achieved this flow before when using OkHttpClient directly, but I don't know how to achieve this in Retrofit.

Maybe something related to this open issue about a ResponseInterceptor?

If there's no straight-forward way to achieve this in retrofit, what would be the best way to implement it? A base listener class?

I'm using RoboSpice with Retrofit as well, if it can be helpful in such case.

like image 557
Hassan Ibraheem Avatar asked Feb 25 '14 12:02

Hassan Ibraheem


1 Answers

Since I'm using RoboSpice, I ended up doing this by creating an abstract BaseRequestListener.

public abstract class BaseRequestListener<T> implements RequestListener<T> {

    @Override
    public void onRequestFailure(SpiceException spiceException) {
        if (spiceException.getCause() instanceof RetrofitError) {
            RetrofitError error = (RetrofitError) spiceException.getCause();
            if (!error.isNetworkError() 
                && (error.getResponse().getStatus() == INVALID_ACCESS_TOKEN_STATUS_CODE)) {
                //I'm using EventBus to broadcast this event,
                //this eliminates need for a Context
                EventBus.getDefault().post(new Events.OnTokenExpiredEvent());
                //You may wish to forward this error to your listeners as well,
                //but I don't need that, so I'm returning here.
                return;
                }
         }
         onRequestError(spiceException);
    }

    public abstract void onRequestError(SpiceException spiceException);
}
like image 67
Hassan Ibraheem Avatar answered Oct 16 '22 21:10

Hassan Ibraheem