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

Error method on Angular rxjs subscription not beeing executed at all

I’ve a component that makes a http request to nodejs backend.
The component is using a service without using ngrx.

The problem is that when i receive an error response from backend, it doesn’t execute the code from error method on the subscribe. I’m able to see the status code and message from devtools only.
The code in ‘next’ callback is working properly.
Here is the Angular code

component:

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.httpCF
      .getPercentagesByName(this.name)
      .subscribe({
        next: (response) => {
          console.log('response get by name');
          console.log(response); // working properly
        },
        error: (error) => {
          console.log('error'); // not rendering at all... Even with error responses
        },
      });

service:

  getPercentagesByName(name: string) {
    return this.http.post(
      environment.ApiGetByName,
      { name: name },
      { headers: this.headers }
    );
  } 

NodeJs response:

res.status(404).send({ msg: 'Element not found' })

Also tested with

res.status(404).json({ msg: 'Element not found' })

But Angular still cannot execute the error method in the subscription…
What i am doing wrong?

EDIT: (required in answers)

HttpInterceptor:

export class TokenInterceptor implements HttpInterceptor {
      constructor(
        private auth: AngularFireAuth,
        private router: Router,
        private _snackBar: MatSnackBar
      ) {}
    
      intercept(
        request: HttpRequest<any>,
        next: HttpHandler
      ): Observable<HttpEvent<any>> {

        return next.handle(request).pipe(
          catchError((error: HttpEvent<any>) => {
            if (error instanceof HttpErrorResponse) {
              if (!(error.error instanceof ErrorEvent)) {

                if (error.status === 401) {
                  // if token expired, logout and navigate to login
                  this.auth.signOut().then(() => {
                    if (this.router.url !== '/auth/login') {
                      this._snackBar.open(
                        'Session expired, please login...',
                        'Close',
                        {
                          duration: 5000,
                          panelClass: 'expiredtoken',
                        }
                      );
                      this.router.navigate(['/auth/login']);
                    }
                  });
                }
              }
            }
            return of(error);
          })
        );
      }
    }

>Solution :

In your interceptor, replace return of(error); with return throwError(() => error);

Reason: of(error) is not considered an error and will not be caught by subscribe({..., error: (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