Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle error response with retrofit + coroutines

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 ?

like image 785
A.Rubinstein Avatar asked Apr 21 '19 07:04

A.Rubinstein


People also ask

How do you handle retrofit response?

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.

How do you catch exceptions in coroutines?

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.

What is call adapter in retrofit?

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.


1 Answers

try/catch the await as recommended by @JakeWharton in this issue

try {
    youService().await()
} catch(ex: HttpException) {
    // do your handling here
}
like image 195
musooff Avatar answered Nov 05 '22 21:11

musooff