Breaking News

LightBlog

Wednesday 7 March 2018

Global exception handling angular 2/5

In this article, I'll explain you Global exception handling angular 2/5




Starting a new project
First, use your terminal to navigate to a directory that will be the parent directory of your project, then run this command:
ng new app-name

Serve project

ng serve

Add a class file error handler

import { Injectable, Optional, Injector, EventEmitter, ErrorHandler } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  public router: Router;
  public isInErrorState = false;
  public errorEvent: EventEmitter<boolean> = new EventEmitter<boolean>(true);
  constructor(private injector: Injector) { }

  handleError(error) {
    console.log('Error handle', error);
    this.router = this.injector.get(Router);
    if (!this.isInErrorState) {
      this.isInErrorState = true;
      setTimeout(() => { this.router.navigate(['/error']); }, 1000);
    }
  }
}

Change app module

import { NgModule, ErrorHandler } from '@angular/core';
import { GlobalErrorHandler } from './shared/common/errorhandler';

providers: [{
  provide: ErrorHandler,
  useClass: GlobalErrorHandler
}],

Generate error.component.ts


import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-error',
    templateUrl: './error.component.html'
})

export class ErrorComponent implements OnInit {
    constructor() { }
    ngOnInit() {
    }
}

Change in error.component.html
<h1>something wen't wrong </h1>


Add error component route in routing file

{ path: 'error', component: ErrorComponent }

No comments:

Post a Comment