Handling specific errors by sending another request transparently in retrofit

泪湿孤枕 提交于 2019-12-20 16:14:14

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/22014958/handling-specific-errors-by-sending-another-request-transparently-in-retrofit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!