gpt4 book ai didi

java - 如何区分没有互联网连接时抛出的异常与没有可用服务器/或错误 URL 的情况?

转载 作者:行者123 更新时间:2023-12-02 09:06:42 29 4
gpt4 key购买 nike

我有这个 when(kotlin)/switch case(java) ,它为我的请求获取 java.net 异常。问题是它在两种情况下抛出 UnknownHostException:

  1. 当我没有连接时。

  2. 当我插入损坏的网址时(这相当于服务器完全不可用)。

如果这两种情况抛出相同的异常,我如何区分它们?我应该在每次请求之前检查用户的连接吗?

何时/ try catch

            is SocketTimeoutException -> {
//Server takes too long to respond
}
is UnknownHostException -> {
//No connection and broken url / no server at all
}
is HttpException -> {
//server error response
}
else -> {
//Any other case
}

最佳答案

你需要在 OkHttpClient 中创建一个像拦截器一样的异常:
在 OkHttpClient 中: .addInterceptor(ConnectivityInterceptor(context))


class ConnectivityInterceptor(private val mContext: Context) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Chain): Response {
if (!NetworkUtil.isOnline(mContext)) {
throw NoInternet()
}
val builder = chain.request().newBuilder()
return chain.proceed(builder.build())
}

}


class NoInternet : IOException() {

override val message: String?
get() {
return "No connectivity exception"
}

}

class NetworkUtil {
companion object {
fun isOnline(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
}
}

你在when中使用

       is NoInternet -> {
}

关于java - 如何区分没有互联网连接时抛出的异常与没有可用服务器/或错误 URL 的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759372/

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