A example that shows to use http interceptors for handle error or adding headers while request conditionally in angular 2+ application
Import the incepters in app.module.ts file
import { HttpErrorInterceptor } from './interceptors/error-interceptor';
import { HttpConfigInterceptor} from './interceptors/httpconfig.interceptor';and use in providers section in NgModule
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true,
},
{
provide: HTTP_INTERCEPTORS,
useClass: HttpConfigInterceptor,
multi: true
}
] catchError( (error: HttpErrorResponse) => {
let errMsg = 'My own error message, status :' + error.status || 0;
return throwError(errMsg);
})
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
const conditionForBypass = request.url.indexOf('google') == -1;
if(conditionForBypass) {
request = request.clone({ headers: request.headers.set('Authorization', 'XYZ') });
}
return next.handle(request);
}