sandwich
sandwich copied to clipboard
How to get body payload error when ApiResponse is used?
I'm trying to get the response body error from an endpoint, but apparently none available method return it.
Would it be possible to get the body error?
GET /cart/add/123 HTTP400 - 400 Bad Request Content-type: application/json
{
"success": false,
"error": "Cart exceed the maximum allowed items (3)"
}
Where I'm trying to get the error payload
viewModelScope.launch {
_state.update { it.copy(isLoading = true) }
apiRepository.addItemToCart(productId, quantity)
.onSuccess {
Timber.d("CartViewModel - Successfully added item to cart: productId=$productId, new total items: ${data.data?.totalItems ?: 0}")
_state.update {
it.copy(
isLoading = false,
cartData = data.data,
error = null
)
}
}
.onError {
Timber.e("CartViewModel - Error adding items. Error: $messageOrNull, Raw: ${payload.toString()}")
_state.update {
it.copy(
isLoading = false,
error = messageOrNull // Use the potentially more specific error message
)
}
}
.onException {
Timber.e("CartViewModel - Exception adding item to cart: productId=$productId")
_state.update {
it.copy(
isLoading = false,
error = "Network error: ${message()}"
)
}
}
}
message(), messageOrNull and payload return always the same:
HttpResponse[http://domain.net/cart/add/123, 400 Bad Request]
Hi @aroeiraio, you can just directly access the error payload instance inside the onError extension. You can check out the details on the doc.