gpt4 book ai didi

android - java.net.UnknownHostException 无法使用 RxJava 转换为 retrofit2.adapter.rxjava.HttpException

转载 作者:太空狗 更新时间:2023-10-29 15:50:44 33 4
gpt4 key购买 nike

我在日志中收到此错误:

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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com