您应该继承IOException
的子类,并使用该子类将信息从拦截器发送到调用代码。
我们认为诸如IllegalStateException
之类的其他异常是应用程序崩溃,不要将它们发送到线程边界之外,因为我们不想让大多数调用者都无法捕获它们。
,
您可能会在自定义 Interceptor
中捕获异常并返回带有某些特定 message
和 code
的空响应。我已经实现了一个自定义 Interceptor
来处理诸如没有互联网连接或互联网连接速度慢等情况......实际上协程的挂起函数在处理网络调用时会抛出异常。根据我的经验,您可以遵循两种方法。 1. 将您的所有网络调用包装在 try...catch
或 2. 创建自定义 Interceptor
并在那里处理异常并返回一些特定响应。 >
方法 1:
try {
webservice.login(username,password)
} catch (e: Exception) {
//...
}
方法 2:
创建自定义 Interceptor
并在那里处理异常。
class LoggingInterceptor : Interceptor {
@Throws(Exception::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
try {
val response = chain.proceed(request)
val bodyString = response.body()!!.string()
return response.newBuilder()
.body(ResponseBody.create(response.body()?.contentType(),bodyString))
.build()
} catch (e: Exception) {
e.printStackTrace()
var msg = ""
when (e) {
is SocketTimeoutException -> {
msg = "Timeout - Please check your internet connection"
}
is UnknownHostException -> {
msg = "Unable to make a connection. Please check your internet"
}
is ConnectionShutdownException -> {
msg = "Connection shutdown. Please check your internet"
}
is IOException -> {
msg = "Server is unreachable,please try again later."
}
is IllegalStateException -> {
msg = "${e.message}"
}
else -> {
msg = "${e.message}"
}
}
return Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(999)
.message(msg)
.body(ResponseBody.create(null,"{${e}}")).build()
}
}
}
我已经为 LoggingInterceptor
的完整实现创建了要点,并带有请求和响应的打印日志。 LoggingInterceptor
,
我不知道您到底需要什么,但是这样理解:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
// todo deal with the issues the way you need to
if (response.code() == SomeCode) {
//do something
return response;
}
return response;
}
})
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(url)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
本文链接:https://www.f2er.com/3165227.html