JakeWharton/retrofit2-kotlin-coroutines-adapter

Exception Handling

Closed this issue · 2 comments

@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>>>

}`

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
}

Yep. What they said.

@Test fun bodyFailure() = runBlocking {
server.enqueue(MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST))
val deferred = service.body()
try {
deferred.await()
fail()
} catch (e: IOException) {
}
}