Showing posts with label Global Error. Show all posts
Showing posts with label Global Error. Show all posts

Monday, July 29, 2019

Angular CLI - Handle Error Globally

To handle error globally in Angular 7 Cli, follow below steps

Ref: https://angular.io/api/core/ErrorHandler

Steps:

- Create ErrorHanlder file as below


import { Injectable, ErrorHandler } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor(private ngZone: NgZone) {
  }

  handleError(error) {
    this.ngZone.run(() => {
//use ngZone to attach context to Angular's zone
//custom logic to do anything, for ex: toastService can be injected and shown here
    });

    //log as error to console
    console.error(error);
  }
}



-  Inject GlobalErrorHandler into app.module.ts providers as below


import { NgModule, ErrorHandler } from '@angular/core';
import { GlobalErrorHandler } from './core/config/error.handler';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
  ],
  providers: [
    …,
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


-  Now throw error from anywhere, it will be catched in GlobalErrorHanlder

import { catchError, map } from 'rxjs/operators';

import { Observable, of, throwError } from 'rxjs';
….

getUser(): Observable<User> {
      return this.http.get(this.getUserUrl      )
        .pipe(
        map(response => { return <User>response; }),
        catchError((error, caught) => {
          //handled error globally
          return throwError(error);
        }));

    }