Hi I have a delete request that works fine, but wh...
# android
s
Hi I have a delete request that works fine, but when I make subsequent delete calls to an item that has already been deleted in the API, I get an Exception, and the app crashes. I tried handling the error using Try/Catch with different exceptions eg(HttpException, IOException, etc) to prevent the app from crashing but it doesn't seem to work.
Copy code
private fun deleteFavourite(
    favourite: GetFavourite?,
    viewModel: WallpapersSharedViewModel
) {
    //handling 404 error in case of subsequent Delete request
    try {
        if (favourite != null && !favourite.isEmpty()) {
            val favouriteId = favourite.get(0).id
            viewModel.deleteFavourite(favouriteId)
            Log.i("hiiiiyaa", "deleted${favouriteId}")
        }
    }
    catch (e: HttpException){
        Log.i("hiiiiyaa", "cannot find item to delete in the Api")
    }
}
Error:
Copy code
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.catexplorer, PID: 28492
    retrofit2.HttpException: HTTP 400 
        at retrofit2.KotlinExtensions$await$2$2.onResponse(KotlinExtensions.kt:53)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:161)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
      ............
🧵 1
p
That is the default retrofit behavior, you should try/catch Http and IO exceptions and map them to your respective error type or use a custom call adapter. Eg: https://github.com/haroldadmin/NetworkResponseAdapter
You may not be catching the Retrofit HttpException but the another HttpException , check your import match the right one
s
Thanks I'll check the out
i confirmed its the right import (`retrofit2.HttpException)
p
did you clean project , uninstall previous app on device, sounds bizarre
Oh wait I believe you are not catching in the right place, your function is not suspend
s
Okay I'm gonna try that
Oooh
p
So you basically are calling the real network somewhere inside your viewModel
s
Yes I am calling it from a viewmodel.. but I also have a repository and a remoteDataSource
where do u think is the right place to catch ?
p
is the retrofit call suspend or it return a result like Call<Y>/Response<T>
s
Yes it's suspend.. but it doesn't return anything
p
Cool! then you have to try/catch around the repository.deleteFav() call. Forward your function parameters there and handle everything there.
👍 1
s
Okay .. thanks alot
👍 1
387 Views