Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop error propagation in an Angular interceptor

I have a http interceptor in my Angular app:

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

  constructor(private messageService: MessageService) {}

  intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> {
    return next
      .handle( req ).pipe(
        tap(event => {
          if (event instanceof HttpResponse) {
            Logger.log('Successful HTTP request in interceptor');
          }
        }, (error: any) => {
          const notFoundError = ErrorCodes.getErrorDescription(error.status);
          if (notFoundError) {
            this.messageService.show(errorMessage);
          } else {
            return Observable.throw( error );
          }

        }
      ));
  }
}

When there is a notFoundError, my app correctly shows the message I want, but it seems the error propagates back to the error handler in the service and I get a "ERROR Error: Uncaught (in promise): HttpErrorResponse" in the console. Is there a way to stop errors in an interceptor?

I mean I would handle common errors here and only propagate others back to the services.

like image 617
JohnnyK Avatar asked Oct 29 '25 13:10

JohnnyK


1 Answers

I'm doing this with rxjs 6:

import {EMPTY} from 'rxjs';

//in your try/catch, interceptor, if statement, etc. 
return EMPTY;

From documentation:

Creates an Observable that emits no items to the Observer and immediately emits a complete notification.

like image 93
Anthony Avatar answered Oct 31 '25 04:10

Anthony