1

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.

Maffe
  • 430
  • 6
  • 14
  • can you add a stackblitz please ... I have same thing in my add and it works correctly – bubbles Nov 30 '20 at 13:25
  • @bubbles are you using HttpInterceptor and PrimeNG messageService? – Maffe Nov 30 '20 at 16:14
  • @bubbles is your application on GitHub or on other open source folders? I'd like to take a look at the code to check what is wrongly configured in mine! – Maffe Dec 01 '20 at 13:00
  • you can add your code here https://stackblitz.com/ and I'll take a look – bubbles Dec 01 '20 at 13:23

2 Answers2

0

had u declare and call for the toaster at desire location? eg. at x-page.module, u need to declare where the toaster/function/whatever is and in x-page.ts calling it

vinz
  • 11
  • 1
0

add to "deps" array in app.module

   {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorInterceptor,
      multi: true,
      deps: [AuthService, MessageService],
    }