https://kotlinlang.org logo
#android
Title
# android
m

mending3

06/17/2020, 3:05 PM
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

Rémy

06/17/2020, 3:08 PM
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

mending3

06/17/2020, 3:10 PM
Thanks for your response. do you have any snippet of it/
?
j

Joost Klitsie

06/17/2020, 3:15 PM
Well the request successfully made the round trip
so you have to check the response body for errors
r

Rémy

06/17/2020, 3:16 PM
if you use Retrofit, with OkHttp, you can add an Interceptor to OkHttp client.
j

Joost Klitsie

06/17/2020, 3:16 PM
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

mending3

06/17/2020, 3:18 PM
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

mending3

06/17/2020, 3:23 PM
@Rémy thanks, but it's really verbose code you got there. I'd better looking ugly than beating around the bush.
r

Rémy

06/17/2020, 3:24 PM
I understand.