簡體   English   中英

Android Kotlin“withTimeout”協程如何處理異常

[英]Android Kotlin "withTimeout" coroutine how to handle exception

I'm using retrofit2 to call API with kotlin coroutines but the API has status code 200, 400 and 700. When request the API and response status code was 400 or 700, which the "withTimeout" coroutine can be exception crash. 我想用“withTimeout”協程或如何自定義“CoroutineScope”來處理狀態碼 400 和 700 響應消息,謝謝。

這是我的代碼

 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)
    }
}

錯誤信息

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)

實際上應該處理SocketTimeoutException ,但是在這里你可以在這里處理泛型Exception ,稍后檢查你的異常是SocketTimeoutException、JsonSyntaxException、UnknownHostException、ConnectException 還是其他。

所以,你可以試試這個。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM