Android 改装句柄 onFailure() 响应



我一直在开发Android应用程序,其中正在使用Retrofit

在那如何处理onFailure(Throwable t) NoInternetConnectionOtherError 的回调

我已经检查了一些关于堆栈溢出的问题,但它没有帮助,因为我使用的是改造 2

compile 'com.squareup.retrofit2:retrofit:2.1.0'

回调代码

    public class AvsCallBack<T> implements Callback<T> {
        private static final String TAG = "AvsCallBack";
        private AvsCallbackInterface<T> avsInterface;
        private Activity activity;
        private boolean validateError = true;
        public AvsCallBack(Activity activity, AvsCallbackInterface<T> avsInterface) {
            this.activity = activity;
            this.avsInterface = avsInterface;
        }
        public AvsCallBack(Activity activity, AvsCallbackInterface<T> avsInterface, boolean validateError) {
            this.activity = activity;
            this.avsInterface = avsInterface;
            this.validateError = validateError;
        }
        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if (response.isSuccessful()) {
                if (BuildConfig.DEBUG) Log.d(TAG, new Gson().toJson(response.body()));
                avsInterface.onSuccess(call, response.body());
            } else {
                onFailure(call, null);
            }
        }
        @Override
        public void onFailure(Call<T> call, Throwable t) {
            if (validateError) {
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Retrofit Exception -> " + ((t != null && t.getMessage() != null) ? t.getMessage() : "---"));
                if (t != null && (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof ConnectException)) {
                    if (t instanceof SocketTimeoutException || t instanceof TimeoutException) {
                        ((BaseActivity) activity).showToast("Oops something went wrong");
                        //avsInterface.onError(call, new AvsException("Oops something went wrong, please try again later..."));
                    } else {
                        ((BaseActivity) activity).showToast("Please check your internet connection...");
                        //avsInterface.onError(call, new AvsException("Please check your internet connection..."));
                    }
                } else {
                   ((BaseActivity) activity).showToast("Oops something went wrong");
                }
                if (BuildConfig.DEBUG)
                    Log.d(TAG, "Avs Exception -> " + ((t != null && t.getMessage() != null) ? t.getMessage() : "---"));
            }
            avsInterface.onError(call, t);
        }
    }

我的界面

public interface AvsCallbackInterface<T> {
    void onSuccess(Call<T> call, T t);
    void onError(Call<T> call, Throwable throwable);
}

引用这里:

Throwable传递给失败时,回调是一个 IOException,这意味着这是网络问题(套接字 超时、未知主机等(。任何其他异常都意味着某些东西 在序列化/反序列化数据时中断,或者它是一个 配置问题。

您可以执行t instanceof IOException来确定网络问题和 做出适当的反应。

401(或任何非2xx响应代码(实际上将转到响应 回调,因为它是一个成功的响应,即使它可能不是 已在服务器上成功操作。您可以在 通过调用response.isSuccess() onResponse

我所做的是使用拦截器进行请求,该拦截器检查互联网连接并做出相应的响应。就我而言,我使用MPV,因此它会自动调用BasePresenter方法。

拦截 器:

class NetworkStatusInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            if (!Util.isInternet(mContext)) {
              return new Response.Builder()
                      .code(1007)
                      .request(chain.request())
                      .protocol(Protocol.HTTP_2)
                      .body(ResponseBody.create(MediaType.parse("{}"),"{}"))
                      .message(mContext.getString(R.string.warning_no_internet))
                      .build();
            }
            return chain.proceed(chain.request());
        }
    }

将拦截器附加到 OkHTTPClient:

 builder.addInterceptor(new NetworkStatusInterceptor());

您可以在 onResponse 中处理此问题:

public void onResponse(final Call<T> call, final Response<T> response) {
        if (response.code() == 1007) {
          // handle no internet error
       }
    }

最新更新