Android Kotlin“withTimeout”协程如何处理异常

lea*_*f76 5 android kotlin kotlin-coroutines

我使用 Retrofit2 通过 kotlin 协程调用 API,但 API 的状态代码为 200、400 和 700。当请求 API 和响应状态代码为 400 或 700 时,“withTimeout”协程可能会异常崩溃。我想使用“withTimeout”协程处理状态代码 400 和 700 响应消息,或者如何自定义“CoroutineScope”,谢谢。

这是我的代码

 suspend fun getLogin() {
    try {
        var result = withTimeout(5_000) {  // <----this line can be crashed with http code 700
            accountService.getLogin(
               LoginRequest() // request data
            ) // retrofit
        }
        when (result.state_code) { // api response state code
            200 -> {
                 Timber.i("Create account got data: ${result.source}")
            }
            400 -> {
                 //....... handle this status code error
            }
            700 -> {
               //....... handle this status code error
            }
        }
    } catch (e: ApiError) {
        throw ApiError("Unable to login", e)
    }
}
Run Code Online (Sandbox Code Playgroud)

错误信息

2020-04-26 22:55:10.384 28895-28895/com.mgear.mednetapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mgear.mednetapp, PID: 28895
retrofit2.HttpException: HTTP 700  
    at retrofit2.KotlinExtensions$await$2$2.onResponse(KotlinExtensions.kt:53)
    at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:150)
    at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:504)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at java.lang.Thread.run(Thread.java:919)
Run Code Online (Sandbox Code Playgroud)

Ami*_*pta 2

实际上, 应该处理SocketTimeoutException ,但是在这里您可以在这里处理通用异常,然后检查您的异常是否是SocketTimeoutException、JsonSyntaxException、UnknownHostException、ConnectException 或其他异常。

所以,你可以尝试这个。

suspend fun getLogin() {
 try {
 //Your api call code here.
 }catch (e: Exception) {
    e.printStacktrace();
    //throw ApiError("Unable to login", e)
 }
}
Run Code Online (Sandbox Code Playgroud)