Error method on Angular rxjs subscription not beeing executed at all

yotube
0

Issue

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:

 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), ...})



Answered By - Jeffrey Ram

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top