Skip to content

Instantly share code, notes, and snippets.

@dmitriy-chernysh
Last active April 24, 2020 19:22
Show Gist options
  • Save dmitriy-chernysh/dae104f913aa3dd836f280559511e447 to your computer and use it in GitHub Desktop.
Save dmitriy-chernysh/dae104f913aa3dd836f280559511e447 to your computer and use it in GitHub Desktop.
OkHttp Interceptor to handle errors
/**
* Interceptor to handle connection errors and return a readable message to user
* <p>
* Created by Dmitriy Chernysh on 12/3/19.
* <p>
* https://instagr.am/mobiledevpro
* #MobileDevPro
*
*
* NOTE: add this to:
*
* OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
* httpClient.interceptors().add(new HandleHttpErrorsInterceptor(context));
*
*
*/
public class HandleHttpErrorsInterceptor implements Interceptor {
private Context mAppContext;
public HandleHttpErrorsInterceptor(Context appContext) {
mAppContext = appContext;
}
@Override
public Response intercept(Chain chain) throws IOException {
try {
return chain.proceed(chain.request());
} catch (ConnectException | SocketTimeoutException e) {
throw new IOException(
mAppContext.getResources().getString(R.string.message_check_internet_connection)
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment