class CoroutineResultExceptionViewModel( private val service: CoroutineExampleService, private val converter: Converter ) : CoroutineScope, ViewModel() { private val job: Job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job init { launch { try { try { getResources().forEach(::println) } catch (exception: ServiceException) { if (exception.code == "ERROR_USER_NOT_LOGGED_IN") throw UserLoggedOutException(exception) else throw exception } } catch (exception: UserLoggedOutException) { exception.printStackTrace() } } } private suspend fun getResources(): List { val response: Response> = service .resources() .await() val body: List? = response.body() if (body != null) { return body } val errorBody: ResponseBody = response.errorBody() ?: throw MissingErrorBodyException() throw converter.convert(errorBody) ?: EmptyConversionException(errorBody) } override fun onCleared() { super.onCleared() job.cancel() } }