angular 2 - show error message for any exception

10,219
  1. Create NotificationService in shared directory

    import { Injectable } from '@angular/core';
    import { Message } from 'primeng/primeng';
    
    @Injectable()
    export class NotificationService {
        message: Message[];
    
        constructor() {
            this.message = [];
        }
    
        success(detail: string, summary?: string): void {
            this.message.push({
                severity: 'success', summary: summary, detail: detail
            });
        }
    
        info(detail: string, summary?: string): void {
            this.message.push({
                severity: 'info', summary: summary, detail: detail
            });
        }
    
        warning(detail: string, summary?: string): void {
            this.message.push({
                severity: 'warn', summary: summary, detail: detail
            });
        }
    
        error(detail: string, summary?: string): void {
            this.message.push({
                severity: 'error', summary: summary, detail: detail
            });
        }
    }
    
  2. create a custom ExceptionHandler (ErrorHandler in RC 6) in shared directory

    import { ErrorHandler, Inject } from '@angular/core';
    import { NotificationService } from './notification.service';
    
    
    export class CustomErrorHandler implements ErrorHandler {
    
        constructor(@Inject(NotificationService) private notificationService: NotificationService) {
        }
    
        handleError(error: any): void {
            this.showErrorInConsole(error);
            setTimeout(() => 
                this.notificationService.error(error.json().Message), 1);
        }
    
        private showErrorInConsole(error: any) :void {
            if (console && console.group && console.error) {
                console.group("Error Log");
                console.error(error);
                console.error(error.message);
                console.error(error.stack);
                console.groupEnd();
            }
        }
    }
    
  3. update AppModule for overriding default error handler

    import { GrowlModule } from 'primeng/primeng';
    ...
    import { NotificationService } from './shared/notification.service';
    import { CustomErrorHandler } from './shared/custom-error-handler';
    
    @NgModule({
        imports: [
            ...,
            GrowlModule // prime ng notification
        ],
        declarations: [
            ...
        ],
        providers: [
            ...,
            NotificationService, // added
            { provide: ErrorHandler, useClass: CustomErrorHandler } // overrride default error handler
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  4. finally in AppComponent:

    import { Component } from '@angular/core';
    import { Message } from 'primeng/primeng';
    import { NotificationService } from './shared/notification.service';
    
    
    @Component({
        selector: 'my-app',
        template: `
            <p-growl [value]="getMessages()"></p-growl>
        `
    })
    export class AppComponent{
        constructor(private notification: NotificationService) {
        }
    
        getMessages(): Message[] {
            return this.notification.message;
        }
    }
    
Share:
10,219

Related videos on Youtube

pavelb
Author by

pavelb

Updated on September 14, 2022

Comments

  • pavelb
    pavelb over 1 year

    I'm trying to do the following in Angular 2 (typescript): For each error (especially errors from the backend server) - present the error to the user (in the UI) - in the main component (mainly since I do't want to write same code in each component).

    Is it a simple way to do it? I guess what I need is a way to set an "error" member in the main component? How do I do it if I override ExceptionHandler?

    thanx, Pavel.

  • Chris Peacock
    Chris Peacock about 6 years
    In case it helps anyone, I had to use the following in my template: <p-growl [(value)]="this.notificationService.messages"></p-growl> in order to get the binding to work correctly, notificationService being made a public member of the component.