0

I'm trying to consume an RESTful API with my Angular 12 client side application, but i'm having some problems to handle HTTP Response Code different than 200. I'm expecting messages like 402, 400 and 401. I've tried creating a HTTP Interceptor to handle this errors, but i can't remove the console error.

Console response

@Injectable()
export class HttpErrorsInterceptor implements HttpInterceptor {

    constructor(private tokenService: TokenService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${this.tokenService.getJwtToken()}`
            }
        });

        return next.handle(request).pipe(
            tap((res: any) => { return res }),
            catchError(this.handleError)
        );
    }

    private handleError(error: any) {
        if (error instanceof ErrorEvent) {
            console.error('Client side network error occurred:', error.error.message);
        } else {
            console.error('Backend - ' +
                `status: ${error.status}, ` +
                `statusText: ${error.statusText}, ` +
                `message: ${error.error.message}`);
        }

        return throwError(error || "server error");
    }
}

The last two console.error are created by me, but i want some strategy to remove all of these 3 errors, because i'm expecting 4xx responses, it isn't a server error.

João Pedro
  • 115
  • 1
  • 12
  • 2
    The first error message is generated by the browser upon a failed HTTP request. See here to disable it in Chrome: https://stackoverflow.com/a/30847631/6513921 – ruth Nov 11 '21 at 15:31
  • @MichaelD but when i recieve an HTTP failed message i can't use the complete expression, is there any way to do this? – João Pedro Nov 11 '21 at 15:39
  • 1
    `complete` and `error` callbacks are mutually exclusive. When `error` is triggered, the observable is already closed and `complete` will not be called. Instead you could either use the [`catchError`](https://rxjs.dev/api/operators/catchError) operator (which will only be triggered on errors) or [`finalize`](https://rxjs.dev/api/operators/finalize) operator (which would be triggered on either `error` or `complete`). – ruth Nov 12 '21 at 07:29

0 Answers0