Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit2 SocketTimeOutException

Tags:

I setup for Retrofit:

private Interceptor interceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtil.isNetworkAvailable()) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response response = chain.proceed(request); //Exception here

            if (NetworkUtil.isNetworkAvailable()) {
                String cacheControl = request.cacheControl().toString();
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", cacheControl)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 7;
                response = response.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
            return response;
        }
    };

And I use to setup cache:

builder = new OkHttpClient.Builder()
                    .cookieJar(new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(Apploader.context)))
                    .addNetworkInterceptor(interceptor)
                    .addInterceptor(interceptor)
                    .cache(cache)
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

Sometime when server response too long My Application crash because SocketTimeOut

It break on line: Response response = chain.proceed(request); as I comment. SocketTimeOut is subclass of IOException, why my code can't catch it. How do I resolved this problem.