I am currently trying to implement a global error handler in my application using PrimeNG 9 messageService and Angular 8 HttpInterceptor. My code is the following:
app.component.html
//....
<p-toast key="notification" position="top-right"></p-toast>
app.module.ts
providers: [ ...
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
},
...
errror-interceptor.interceptor.ts
import { Injectable, ɵConsole } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { MessageService } from 'primeng/api';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ErrorInterceptor implements HttpInterceptor {
constructor(
private messageService: MessageService,
private router: Router
) {}
public intercept(httpRequest: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> {
if (httpRequest.method !== 'GET')
return next.handle(httpRequest);
else {
return next.handle(httpRequest).pipe(
catchError( (err: HttpErrorResponse) => {
console.log(err)
this.messageService.add({
key: 'notification',
severity: 'error',
summary: 'Woops! There was an error!',
});
return throwError(err);
})
);
}
}
The interceptor successfully catches errors and prints them in the console. However, the toast is never displayed. I also point out that i make use of messageService in other components and the toasts are correctly displayed, it just does not work in the interceptor.