Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 - show error message for any exception

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.

like image 910
pavelb Avatar asked Aug 16 '16 20:08

pavelb


1 Answers

  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;
        }
    }
    
like image 163
hadi Avatar answered Sep 30 '22 19:09

hadi