我在日志中收到此错误:
Caused by java.lang.ClassCastException: java.net.UnknownHostException cannot be cast to retrofit2.adapter.rxjava.HttpException
这就是我的 onError 方法。该错误可能是在设备未连接时导致的。
@Override
public void onError(Throwable e) {
assert e != null;
Timber.d(e);
HttpException exception = (HttpException) e;
assert view != null;
view.hideRefreshSpinner();
if (exception.code() == HttpURLConnection.HTTP_BAD_REQUEST) {
view.showSnackbarInvalidError();
} else {
view.showUnauthorizedError();
}
}
最佳答案
发生这种情况是因为您收到的是 java.net.UnknownHostException
而不是 retrofit2.adapter.rxjava.HttpException
的实例。如果您查看 doc ,它说:
- Direct body (e.g., Observable) calls onNext with the deserialized body for 2XX responses and calls onError with HttpException for non-2XX responses and IOException for network errors.
- Response wrapped body (e.g., Observable>) calls onNext with a Response object for all HTTP responses and calls onError with IOException for network errors
- Result wrapped body (e.g., Observable>) calls onNext with a Result object for all HTTP responses and errors.
所以你收到了一个网络错误。
另见 this
您可以像这样包装您的代码:
@Override
public void onError(Throwable e) {
assert e != null;
Timber.d(e);
if (e instanceof HttpException) {
assert view != null;
view.hideRefreshSpinner();
if (((HttpException) e).code() == HttpURLConnection.HTTP_BAD_REQUEST) {
view.showSnackbarInvalidError();
} else {
view.showUnauthorizedError();
}
}
}
关于android - java.net.UnknownHostException 无法使用 RxJava 转换为 retrofit2.adapter.rxjava.HttpException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41312083/