'How to handle API error response using retrofit with android kotlin
My Android kotlin code:
viewModelScope.launch(Dispatchers.IO) {
_userAuth.postValue((Resource.Loading()))
try {
val res = repository.userSignUp(SignupRequest("test", "[email protected]", "password"))
if (res.isSuccessful) {
res.body()?.let {
_userAuth.postValue(Resource.Success(it))
}
} else {
// Handle error here...
}
} catch (e: IOException) {
Timber.d(e.message)
} catch (e: HttpException) {
Timber.d(e.message)
}
}
}
I developed nodejs api where user can Signup and Signin. How to handle errors if reponse is not successful. My json response error model look like this:
{
"error": {
"message": "Username is already taken",
"code": 422
}
}
error.message property's value could be anything according to error e.g. Email is already taken, Email is invalid, etc. How to parse with own custom kotlin data class?
Solution 1:[1]
Your sealed generic Resource class should also handle the error. Something like this
sealed class Resource<T> {
data class Success<T>(val data: T) : Resource<T>()
data class Error<T>(val error: Throwable) : Resource<T>()
class Loading<T> : Resource<T>()
}
Then, inside VM
if (res.isSuccessful) {
res.body()?.let {
_userAuth.postValue(Resource.Success(it))
}
} else {
// Handle error here...
_userAuth.postValue(Resource.Error(it))
}
In UI, when observing it, simply returning api's own failure message
viewModel._userAuth.observe(viewLifecycleOwner){
when (it) {
is Resource.Success -> onSuccess(it.data)
is Resource.Error -> Toast.makeText(requireContext(), it.error.message, Toast.LENGTH_LONG).show()
is Resource.Loading -> onLoading()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | feigo808 |
