Retrofit + Okhttp + RxJava2 网络库问题总结

目前在稳护老项目,需要在项目中逐步替换老的网络通信框架,所以就手动码了最近挺流行的网络解决方案Retrofit + Okhttp + RxJava2。

现在项目中已经有大约一般的接口更新完成。App发布后,通过Buggly统计,发现这个库有个很大的问题没有处理好。

就在服务出现问题的时候,会出现一些无法捕获的异常。

主要出现在这里:

   /**
     * 添加头部属性的拦截器
     */
    private static class BasicParamsInterceptor implements Interceptor {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            Set> entries = HttpHeaderManger.getHeader().entrySet();
            for (Map.Entry entry : entries) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
             returne  chain.proceed(builder.build());
        }
    }

通过okhtttp 的拦截器添加 公共参数的时候,

 returne  chain.proceed(builder.build());

这一行在服务器出现问题的时候(比如重启、网络断线等),会出现 非 IOException 的异常 而引起崩溃!

所以修正如下:

    /**
     * 添加头部属性的拦截器
     */
    private static class BasicParamsInterceptor implements Interceptor {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            Set> entries = HttpHeaderManger.getHeader().entrySet();
            for (Map.Entry entry : entries) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
            okhttp3.Response proceed;
            try {
                proceed = chain.proceed(builder.build());
            } catch (Exception e) {
                //上报异常
                CrashReport.postCatchedException(new NetBusinessException(
                        e.getMessage(), e.getCause()));
                throw e;
            }
            return proceed;
        }
    }

出现异常后,捕获异常,然后再抛出!

你可能感兴趣的:(Retrofit + Okhttp + RxJava2 网络库问题总结)