You need to create an interceptor. See how to create an interceptor here
In your interceptor you can do something like this. Intercept the response, check for your condition and throw error accordingly.
export class YourInterceptor implements HttpInterceptor{
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
//check for your condition here, if true, return error as follows. This will run your error block.
return Observable.throw(new HttpErrorResponse({status:401, statusText:"Error of auth"}));
}
}
With Angular 6 and (rxjs 6) you can now do it this way
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) //Check if it is a response
{
if(your condition here) //hint: Use event object to get your response
{
throwError('Your error')
}
}
return event;
}));
}