I'm new with coroutines. Trying to use retrofit + coroutines + Jake Wharton's CoroutineCallAdapterFactory by this tutorial
But don't get how to handle json response errors. For example error could be like that:
{
"code": 105,
"error": "invalid field name: bl!ng"
}
I think adding code and error fields (and checking object for null fields) in TmdbMovie class - it's wrong. And then - how to use error fields after launching coroutine in TmdbViewModel ?
Handling Retrofit API Responses and ExceptionsThe handleApi function receives an executable lambda function, which returns a Retrofit response. After executing the lambda function, the handleApi function returns NetworkResult. Success if the response is successful and the body data is a non-null value.
We can add CoroutineExceptionHandler or use try-catch to handle exceptions inside SupervisorScope. For withContext, we can use the same above ways to handle exceptions, just the coroutine builder will be changed & everything inside withContext will be executed sequentially.
By default, this return wrapping is done as Call<TypedResponseClass> type. This action of returning from the background thread, which receives and prepares the result, to the Android UI thread is a call adapter! Basically, call adapters are sitting on top of Retrofit and offer the functionality to you as the developer.
try/catch
the await
as recommended by @JakeWharton in this issue
try {
youService().await()
} catch(ex: HttpException) {
// do your handling here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With