user3561494
user3561494

Reputation: 2342

error handling with Retrofit2 using Kotlin coroutines

I understand how to handle errors when not using coroutines:

@GET("user/{user}")
fun getHomeData(@Path("user") user: String?): Call<HomeDataBody>



fun getHomeData(id:String, callback: (Boolean, String?) -> Unit)
{
    val call = service.getHomeData(id)
    call.enqueue( object : Callback<HomeDataBody> {
        override fun onResponse(call: Call<HomeDataBody>, response: Response<HomeDataBody>)
        {
            if (response.isSuccessful)
            {
                dataMgr.homeData = response.body()!!.user

                callback(true, null)
            }
            else
            {
                callback(false, response.message())
            }
        }

        override fun onFailure(call: Call<HomeDataBody>, t: Throwable)
        {
            callback(false, t.message)
        }

    })
}

But I cannot for the life of me figure out how to do this with coroutines, this is what I have for a coroutine that does not return errors:

@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): HomeData


suspend fun getHomeDataCoroutine(id:String) : Pair<Boolean, String>
{
    val data = service.getHomeDataCoroutine(id)

    if(data != null)
    {
        dataMgr.homeData = data
    }
    else
    {
        return Pair(false, "how do i get the error message??")
    }

}

I also attempted this, but when I try to call service.getHomeDataCoroutine I get this error: java.lang.IllegalArgumentException: Unable to create call adapter for class java.lang.Object for method RiseServiceRetro.getHomeDataCoroutine

@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): Deferred<HomeDataBody>?

sealed class Result<out T : Any>
class Success<out T : Any>(val data: T) : Result<T>()
class Error(val exception: Throwable, val message: String =    exception.localizedMessage) : Result<Nothing>()

suspend fun getHomeDataCoroutine(id:String): Result<HomeDataBody>
{
    try {
        val response = service.getHomeDataCoroutine(id)!!.await()
        return Success(response)
    } catch (e: Exception) {
        return Error(e)
    }

}

Upvotes: 2

Views: 4753

Answers (1)

Sergio
Sergio

Reputation: 30595

To handle errors when calling suspend function of Retrofit service wrap it in try-catch block:

@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): HomeDataBody

suspend fun getHomeDataCoroutine(id:String): Pair<Boolean, String> {
    return try {
        val data = service.getHomeDataCoroutine(id)
        dataMgr.homeData = data
        Pair(true, "")
    } catch(e: Throwable) {
        Pair(false, e.message ?: "error")
    }
}

Upvotes: 2

Related Questions