目前在穩(wěn)護(hù)老項(xiàng)目现使,需要在項(xiàng)目中逐步替換老的網(wǎng)絡(luò)通信框架恨樟,所以就手動碼了最近挺流行的網(wǎng)絡(luò)解決方案Retrofit + Okhttp + RxJava2漾稀。
現(xiàn)在項(xiàng)目中已經(jīng)有大約一般的接口更新完成躲庄。App發(fā)布后涧郊,通過Buggly統(tǒng)計(jì),發(fā)現(xiàn)這個(gè)庫有個(gè)很大的問題沒有處理好沟于。
就在服務(wù)出現(xiàn)問題的時(shí)候,會出現(xiàn)一些無法捕獲的異常植康。
主要出現(xiàn)在這里:
/**
* 添加頭部屬性的攔截器
*/
private static class BasicParamsInterceptor implements Interceptor {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Set<Map.Entry<String, String>> entries = HttpHeaderManger.getHeader().entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
returne chain.proceed(builder.build());
}
}
通過okhtttp 的攔截器添加 公共參數(shù)的時(shí)候旷太,
returne chain.proceed(builder.build());
這一行在服務(wù)器出現(xiàn)問題的時(shí)候(比如重啟、網(wǎng)絡(luò)斷線等)销睁,會出現(xiàn) 非 IOException 的異常 而引起崩潰供璧!
所以修正如下:
/**
* 添加頭部屬性的攔截器
*/
private static class BasicParamsInterceptor implements Interceptor {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Set<Map.Entry<String, String>> entries = HttpHeaderManger.getHeader().entrySet();
for (Map.Entry<String, String> entry : entries) {
builder.addHeader(entry.getKey(), entry.getValue());
}
okhttp3.Response proceed;
try {
proceed = chain.proceed(builder.build());
} catch (Exception e) {
//上報(bào)異常
CrashReport.postCatchedException(new NetBusinessException(
e.getMessage(), e.getCause()));
throw e;
}
return proceed;
}
}
出現(xiàn)異常后,捕獲異常冻记,然后再拋出睡毒!