方案2:捕获连接超时异常 [英] Retrofit 2: Catch connection timeout exception

查看:1059
本文介绍了方案2:捕获连接超时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(5, TimeUnit.SECONDS);

RestAdapter.Builder builder = new RestAdapter.Builder()
        .setEndpoint(ROOT)
        .setClient(new OkClient(okHttpClient))
        .setLogLevel(RestAdapter.LogLevel.FULL);

我正在尝试处理服务器故障并且用户收到连接超时异常的情况,这是我的日志记录:

I am trying to handle the situation in which my server is down and the user gets a connection timeout exception, this is my logging:

java.net.SocketTimeoutException: failed to connect to /192.168.0.53 (port 3000) after 5000ms

完整记录: http://pastebin.com/gscCGb7x

是否有办法将其路由到改造失败方法中,以便我可以在那里进行处理?

Is there a way to route this into the retrofit failure method so I can handle it over there?

提前谢谢!

推荐答案

用于翻新2

在您的Web服务实例中定义一个侦听器:

Define a listener in your web service instance:

public interface OnConnectionTimeoutListener {
    void onConnectionTimeout();
}

将拦截器添加到您的Web服务:

Add an interceptor to your web service:

public WebServiceClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            return onOnIntercept(chain);
        }
    });
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    webService = retrofit.create(WebService.class);
}

使用try-catch块将Intercep代码括起来,并在发生异常时通知监听器:

Enclose your intercep code with try-catch block and notify listener when exception happens:

private Response onOnIntercept(Chain chain) throws IOException {
    try {
        Response response = chain.proceed(chain.request());
        String content = UtilityMethods.convertResponseToString(response);
        Log.d(TAG, lastCalledMethodName + " - " + content);
        return response.newBuilder().body(ResponseBody.create(response.body().contentType(), content)).build();
    }
    catch (SocketTimeoutException exception) {
        exception.printStackTrace();
        if(listener != null)
            listener.onConnectionTimeout();
    }

    return chain.proceed(chain.request());
}

这篇关于方案2:捕获连接超时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆