Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the error message returned from http interceptor is ignored?

I have an angular project that calls api with HttpInterceptor like below.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(error => this.errorHandler(error)));
}

private errorHandler(response: HttpEvent<any>): Observable<HttpEvent<any>> {
  console.log(response)
throw response;
}

And the api is set up in service file like below

  getData(data1: string): Observable<data2: number> {   
    return this.http.post<{data2: number;>('search/', {data1} );
  }

The api is called in componenet like below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.someService.getData('hi').subscribe( res => {    
    console.log('res wont response because error its find and expected');
}),(err=>{console.log('hello?');console.log(err);} );

I expect "hellow?" console log yet it only return the "response" console log. Why is it skipping the err subscription and how can I make the err subscription works? Thank you.

>Solution :

I think the throw can be the problem. You can try return throw. But the correctly way is to use throwError. My Interceptor (updated to newest RxJS syntax) looks so:

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
  ...
   if (authToken == null) { // Do HERE what you want
      this.router.navigate(['/login']);
      return next.handle(req);
    }

    return next.handle(authRequest as any).pipe(
      catchError((error: any) => {
        if (error['status'] !== 401 && error['status'] !== 403) {
          return throwError(() => error);
        }
  ...
}

So the **return throwError(() => error); does the trick I think.

Update

A wrong syntax in the httpClient is the problem. The correctly is:

this.someService.getData('hi').subscribe( res => {    
    console.log('res wont response because error its find and expected');
  },
  err => {console.log('hello?');console.log(err);
  }
);

But this is deprecated. So the new way is this:

this.someService.getData('hi').subscribe(
  {
    next: (res) => {    
      console.log('res wont response because error its find and expected');
    },
    error: (err) => { console.log('hello?');console.log(err);
    }
  }
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading