How to handle network error responses with retrofit2 hilt in android when network goes offline?

Viewed 384

I am building a simple android app using jetpack compose with MVVM architecture. For this I am using Retrofit2 for network request and Hilt for dependency injection. This App work fine while internet is available but when I turn off internet it crashes the App. So how to handle the network error while app is in offline mode ?

This is code for requesting data to API:

    @Singleton
    @Provides
    fun provideRecipeService() : RecipeService {

        return Retrofit.Builder()
            .baseUrl("https://food2fork.ca/api/recipe/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(RecipeService::class.java)
    }

2 Answers

it has nothing to do with your dependency injection, I think there is a uncatched exception in your code, so when your network call fails (throws Exception) you didn’t handle the exception, go to the network call and cover the whole network call with try-catch and test it, if it was ok, map the exception to error model and handle it in your ViewModel the way you want to treat your errors hope it helped

We need to to actually the exception you are seeing for an exact solution but in general some network states can throw different exceptions. You are safer if you put the network call in a try catch block.

And as keivan shamlu said, it has nothing to do with Compose.

Related