我使用的是Retrofit 1.9.0,RxJava 1.0.10,RxAndroid 0.24.0和OkHttp 2.4.0。当我设置自定义ErrorHandler时,RxJava订阅者方法未被触发。为什么?是否有可能改变这种行为?
我附上了源代码。
初始化:
的HttpClient:
OkHttpClient httpClient = new OkHttpClient();
httpClient.setHostnameVerifier(...); // allow all
try {
httpClient.setSslSocketFactory(...);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
RestAdapter:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_API_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(httpClient)
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept-Language", Locale.getDefault().getLanguage());
}
})
.setConverter(new GsonConverter(gson))
.setErrorHandler(new CustomErrorHandler(this))
.build();
Api api = restAdapter.create(Api.class);
自定义ErrorHandler:
public class CustomErrorHandler implements ErrorHandler {
private final Context mContext;
public UniversalErrorHandler(Context context) {
mContext = context;
}
@Override
public Throwable handleError(RetrofitError cause) {
String errorMessage;
if (cause.getKind() == RetrofitError.Kind.NETWORK) {
errorMessage = mContext.getString(R.string.no_network_connection);
} else {
if (cause.getResponse() == null || cause.getResponse().getStatus() == 500) {
errorMessage = mContext.getString(R.string.error_contacting_server);
} else {
errorMessage = mContext.getString(R.string.unknown_error);
}
}
return new Exception(errorMessage, cause);
}
}
用法:
Observable<List<Object>> observable = api.getObjects();
observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Object>>() {
@Override
public void onCompleted() {
Timber.i("onCompleted");
}
@Override
public void onError(Throwable e) {
Timber.e(e, "onError");
}
@Override
public void onNext(List<Object> objects) {
Timber.i("onNext %d", objects.size());
}
});
答案 0 :(得分:1)
我从代码清单中删除了这一行:
Timber.e("Error: %s, %d", cause.getMessage(), cause.getResponse().getStatus());
getStatus()
导致NullPointerException
因为响应为空...我忽略了它,因为logcat中没有任何日志。
onError()
方法抛出运行时异常,则不会调用 handleError()
。