Retrofit 2: Catch connection timeout exception

后端 未结 7 1291
执念已碎
执念已碎 2020-11-27 03:26

I have the following setup:

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


        
7条回答
  •  甜味超标
    2020-11-27 04:07

    It's a bit more complicated. With Retrofit you can make API calls that are either synchronous or asynchronous.

    If your endpoint returns void and has a callback it is asynchronous. If it returns something and has no callback it's synchronous.

    For asynchronous calls you get this exception in the onFailure(...) method of your callback.

    For synchronous calls you don't get it at all, unless you wrap your call in a try/catch.

    try {
       // your synchronous call goes here  
    } catch (RetrofitError error) {
       // handle errors
    }
    

    Update: The above answer applies to Retrofit 1.9. Retrofit 2.0 has changed this a lot. If you're wondering about how things now work in Retrofit 2.0, this article gives some pointers http://inthecheesefactory.com/blog/retrofit-2.0/en

提交回复
热议问题