JakeWharton / retrofit2-kotlin-coroutines-adapter

A Retrofit 2 adapter for Kotlin coroutine's Deferred type.
Apache License 2.0
1.97k stars 128 forks source link

Exception Handling #10

Closed vados60 closed 6 years ago

vados60 commented 6 years ago

@JakeWharton Please advise how am I supposed to handle Network exceptions when request fails? ex internet is unavailable?

In this case API call instead of Deferred<?> returns nothing and chain breaks here. api.login(username, password).await() -- somewhere inside execution fails and in Logcat I see <-- HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "URL HERE": No address associated with hostname

`interface API {

@GET("login")

fun login(@Query("username") username: String, @Query("password") password: String): Deferred<Response<BaseNetResponse<LoginResponse>>>

}`

zsmb13 commented 6 years ago

You can put a try-catch around this, as the adapter calls Deferred.completeExceptionally when the request fails.

try {
    api.login(username, password).await()
} catch (e: IOException) {
    // handle exception
}
JakeWharton commented 6 years ago

Yep. What they said.

https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter/blob/9362f505c7e7e6c5ab3113641de35fdff4dd583e/src/test/java/com/jakewharton/retrofit2/adapter/kotlin/coroutines/experimental/DeferredTest.kt#L72-L81