Brendan Weinstein
03/10/2020, 2:41 AMUnknownHostException
. I tried to find a clean way to gracefully handle this without ending up with overly nested try-catch logic. What I ended up doing was defining a `CoroutineExceptionHandler`:
val handler = CoroutineExceptionHandler { coroutineContext, throwable ->
if (throwable is UnknownHostException) {
_state.value = _state.value!!.copy(type = StateType.NO_NETWORK)
} else {
throw throwable
}
}
fun onButtonTap() {
viewModelScope.launch {
val response = getSomethingFromNetwork()
if (response.isSuccessful) {
_state.value = _state.copy(SUCCESS_FETCHING_SOMETHING)
}
_state.value = _state.copy(ERROR_FETCHING_SOMETHING)
}
}
Just curious to get folks' feedback to how to best handle an UnknownHostException when defining a network call with suspend functions and retrofit. I am also curious why this exception is thrown as opposed to returning a specific error type. Is it just a remnant from designing libraries for java-land? Or is it still idiomatic to throw an UnknownHostException as a kotlin library?