Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2057
粉色の甜心
粉色の甜心 2021-01-30 23:09

I am using Retrofit 2.6.0 with coroutines for my web service call. I am getting the API response properly with all response codes (success & error cases). My Issue is when I

7条回答
  •  暖寄归人
    2021-01-30 23:46

    Well, that's what I do, just to reduce try-catch junk copypaste

    Declare our API call methods like this

    @GET("do/smth")
    suspend fun doSomething(): SomeCustomResponse
    

    In a separate file

    suspend fun  handleRequest(requestFunc: suspend () -> T): kotlin.Result {
        return try {
            Result.success(requestFunc.invoke())
        } catch (he: HttpException) {
            Result.failure(he)
        }
    }
    

    Usage:

    suspend fun doSmth(): kotlin.Result {
        return handleRequest { myApi.doSomething() }
    }
    

    HTTP codes are handled by Retrofit - it just throws an HttpException if responseCode is not 2xx. So what we should do is just catch this exception.

    I know, it is not a perfect solution, but let's for Jake to invent something better)

提交回复
热议问题