小编Dan*_*iel的帖子

网络错误的异常处理改造

我想知道在使用协程时处理改造请求中的网络错误的最佳方法是什么。

经典方法是在发出请求时在最高级别处理异常:

try {
    // retrofit request
} catch(e: NetworkException) {
    // show some error message
}
Run Code Online (Sandbox Code Playgroud)

我发现这个解决方案是错误的,它添加了很多样板代码,相反我创建了一个返回错误响应的拦截器:

class ErrorResponse : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        return try {
            chain.proceed(request)
        } catch (e: Exception) {
            Snackbar.make(
                view,
                context.resources.getText(R.string.network_error),
                Snackbar.LENGTH_LONG
            ).show()
            Response.Builder()
                .request(request)
                .protocol(Protocol.HTTP_1_1)
                .code(599)
                .message(e.message!!)
                .body(ResponseBody.create(null, e.message!!))
                .build()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个解决方案好一点,但我认为它可以改进。

所以我的问题是:当用户没有互联网连接时,处理这种情况的正确方法是什么,没有大量的样板代码(最好在连接错误的情况下使用全局处理程序)?

android kotlin kotlin-coroutines

4
推荐指数
1
解决办法
4026
查看次数

标签 统计

android ×1

kotlin ×1

kotlin-coroutines ×1