Implemented a small feature from scratch and for t...
# squarelibraries
b
Implemented a small feature from scratch and for the networking I defined suspend functions in a retrofit interface. When testing the feature with airplane mode enabled I had a crash from an uncaught
UnknownHostException
. 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`:
Copy code
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?