```viewModelScope.launch { try { val a...
# android
m
Copy code
viewModelScope.launch {
    try {
        val apiRes = AccountRepository().connect.createAccount(accountName.value, phoneNumber.value?.toInt())
        _showNotif.postValue("success")
    } catch (throwable: Throwable) {
        when (throwable) {
            is IOException -> _showNotif.postValue(throwable.message)
            is HttpException -> _showNotif.postValue("${throwable.code()}")
            else -> _showNotif.postValue(throwable.message)
        }
    }
}
I want to catch an exception from retrofit. the api returns 500. however why does the viewModelScope return me the success message indicated by
_showNotif.postValue("success")
code?
r
If you want to catch a http status code 500, you can do it via an Interceptor right ? Handle the request / response there first, I think.
m
Thanks for your response. do you have any snippet of it/
?
j
Well the request successfully made the round trip
so you have to check the response body for errors
r
if you use Retrofit, with OkHttp, you can add an Interceptor to OkHttp client.
j
Copy code
inline fun <reified T> Call<T>.executeForResult(): Result<T> =
	try {
		val response = execute()
		val body = response.body()
		when {
			response.isSuccessful && body != null -> SUCCESS(body)
			response.isSuccessful && response.code() == 204 && T::class == Any::class -> SUCCESS(Any() as T)
			response.isSuccessful -> ERROR(error = NullPointerException())
			else ->ERROR(error = HttpException(response))
		}
	}
	catch (e: Exception) {
		RsmLog.e(BUSINESS_TAG, e)
		ERROR(error = e)
	}
I have for example this, where it returns a Result object, which can be SUCCESS or ERROR
(or LOADING but in this case not necessary)
so the execute will throw an error only if there is actually something going wrong
like io exception, network error
if you do get a response from the backend, the request was successfully made and returned a response. Just check if the response in itself was successful or not
m
apparently I noticed I've set the Interceptor. but this is ugly.
Copy code
try {
    val apiRes = AccountRepository().connect.createAccount(accountName.value, phoneNumber.value?.toInt())
    if (apiRes.code() == 500) {
        _showNotif.postValue("error 500")
    }
}
it should be caught in the catch block
thank you Joost for joinin in
m
@Rémy thanks, but it's really verbose code you got there. I'd better looking ugly than beating around the bush.
r
I understand.