val client = OkHttpClient.Builder()
.addInterceptor(GlobalErrorHandlerInterceptor{ error->
when(it){
is GlobalError.ClientError->{
println("Client Error Caught! => ${error.error} / ${error.statusCode}")
}
is GlobalError.ServerError->{
println("Server Error Caught! => ${error.error} / ${error.statusCode}")
}
}
})
.build()
Note
add GlobalErrorHandlerInterceptor like previous sample and set that client as retrofit client.
val retrofit = Retrofit
.Builder()
.baseUrl("https://your_beautiful_base_url.com/")
.addConverterFactory(ScalarsConverterFactory.create())
.client(client)
.build()
Ignoring All Errors:
interface Api {
@GET("todos/1")
@IgnoreGlobalErrorHandling(ignoreStrategy = AllErrorsStrategy::class)
fun getTodo():Call<String>
}
Ignoring Client Errors:
interface Api {
@GET("todos/1")
@IgnoreGlobalErrorHandling(ignoreStrategy = ClientErrorsStrategy::class)
fun getTodo():Call<String>
}
Ignoring Server Errors:
interface Api {
@GET("todos/1")
@IgnoreGlobalErrorHandling(ignoreStrategy = ServerErrorsStrategy::class)
fun getTodo():Call<String>
}
Ignoring Just Some Status Codes:
interface Api {
@GET("todos/1")
@IgnoreGlobalErrorHandling(
ignoreStrategy = StatusCodeStrategy::class,
ignoreStatusCodes = [422,501]
)
fun getTodo():Call<String>
}
startKoin{
single{
Channel<GlobalError>()
}
single{
val client = OkHttpClient.Builder()
.addInterceptor(GlobalErrorHandlerInterceptor{ error->
val injectedChannel:Channel<GlobalError> = get()
scope.launch{
injectedChannel.send(error)
}
})
.build()
Retrofit
.Builder()
...
.client(client)
.build()
}
}
class MainActivity: AppCompatActivity{
val injectedChannel:Channel<GlobalError> by inject()
override fun onCreate(savedInstanceState: Bundle?){
...
injectedChannel.receiveAsFlow().collect { error ->
when(error){
is GlobalError.ClientError->{
if(error.statusCode == 401){
// Show toast
// logout
// navigate to login screen
}
}
is GlobalError.ServerError->{
// show server error
}
}
}
}
}
In this example, Any api of yours that gives a status code of 401 will cause the user to log out and navigate to log in screen.
repositories{
...
maven("https://jitpack.io")
}
dependencies{
implementation("com.github.ehsannarmani:OkHttpGlobalErrorHandler:latest")
}