How to intercept the HTTP status code of all requests in Retrofit

Viewed 854

I have a huge code base for an existing project, and it performs many requests all over the app. The issue is that I have to check for a specific error-code of all requests to perform a specific action.! seems simple, but the only way that I can do this is to go on each request and check for that code inside the onError response, and that's gonna take make a lot of time to do because there are many requests on the app (50+).!

Example of a request:

fun getOrders() {
// some code
    when {
        response.isSuccessful -> { // do stuff}
        else -> {
            if (response.code() == 401){
                // delete local user & redirect to Login
            }
            val gson = Gson()
            val errorBase: ListDataBase = gson.fromJson(response.errorBody()?.string(), ListDataBase::class.java)
            ordersResponse.value = Resource.error(null, errorBase.responseMessage, null)
        }
    }
// code..
}

If I have to do this manually, I must do if statement inside the else block for each request I don't wanna do that.

So I tried this:

Inside the Retrofit Client class, I tried to get the code of all requests using the interceptor, but I can only get it by executing the request there which causes a crash!

 okHttpBuilder.addInterceptor { chain ->
                val original = chain.request()
                val requestBuilder = original.newBuilder()
                requestBuilder.header("language", Lingver.getInstance().getLanguage())
                if (Hawk.contains("user")) {
                    val user: User = Hawk.get("user")
                    requestBuilder.header("X-Authorization", user.token)
                }
                val request = requestBuilder.build()
                // line below caused the crash 
                // Logger.e(" CODE -> ${chain.call().execute().code.log()}")
                chain.proceed(request)
            }

And this is the crash

java.lang.IllegalStateException: Already Executed
1 Answers

chain.proceed(request) basically continues the execution of your api and returns response. If you want to check response code you can simply use it like this

val response = chain.proceed(request)
Logger.e(" CODE ->" + response.code)

Here response.code is HTTP code that you want.

Related