Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created April 25, 2025 17:50
Show Gist options
  • Save IlyaGulya/c7dc18314530397cbbf464abea93375b to your computer and use it in GitHub Desktop.
Save IlyaGulya/c7dc18314530397cbbf464abea93375b to your computer and use it in GitHub Desktop.
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import java.io.IOException
// Inner interceptor that simulates a failure
class FailingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
throw IOException("Simulated network error from FailingInterceptor")
}
}
// Outer interceptor that catches IOExceptions from inner interceptors
class CatchingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
return try {
chain.proceed(chain.request())
} catch (e: IOException) {
println("Caught IOException in CatchingInterceptor: ${e.message}")
// Return a dummy response or rethrow as needed
Response.Builder()
.request(chain.request())
.protocol(Protocol.HTTP_1_1)
.code(500) // Internal Server Error
.message("Intercepted Exception")
.body(ResponseBody.create("text/plain".toMediaTypeOrNull(), "Error handled"))
.build()
}
}
}
// Usage
fun main() {
val client = OkHttpClient.Builder()
.addInterceptor(CatchingInterceptor()) // Outer
.addInterceptor(FailingInterceptor()) // Inner
.build()
val request = Request.Builder()
.url("http://localhost/") // URL won't be used because the failure is simulated
.build()
val response = client.newCall(request).execute()
println("Response: ${response.code} - ${response.body?.string()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment