Search code examples
androidkotlintry-catchretrofit

Retrofit Try&Catch is not working as I expected


I can catch IOException by using try&catch but I can't catch HttpException by using try&catch. I tried to catch error code 401 by using if else conditions and it's working.

The question is why try&catch method is not working to catch error code 401 in this situation? What should I do?

override suspend fun wallpaperByTagRepo(tag: String,page: Int): Flow<Resource<List<WallPaper>>> = flow {

       emit(Resource.Loading())

        try {
            val response = remoteDataSource.wallpaperByTagDS(tag, page)
            if (response.isSuccessful){

                val body = response.body()
                body?.let { dto ->
                    val data = dto.toWallPaper()
                    emit(Resource.Success(data = data))
                }
            }
            else{
                when(response.code()){
                    401 -> {
                        Log.w(TAG,"401 Unauthorized")
                    }
                }
            }
        }

        catch (e: IOException){
            emit(Resource.Error("Please check your connection..."))

        }
        catch (e:HttpException){
            emit(Resource.Error("Unexpected error, please try later..."))
            Log.w(TAG,"${e.code()}")

        }

    }

}


Solution

  • Retrofit will not throw retrofit2.HttpException in case of non-2xx HTTP response. In this situation you can manually construct an retrofit2.HttpException object from an unexpected response like:

    try {
        //
        if (response.isSuccessful) {
            //
        } else {
            throw HttpException(response)
        }
    } catch (e: IOException) {
        //
    } catch (e: HttpException) {
        //
    }