Angular, Global Error Handler

GitHub

https://github.com/szalek/AngularGlobalErrorsHandler

/src/app/core/app-error-handler.ts

import {ErrorHandler} from "@angular/core";

export class AppErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    console.log("Global Error Handler: ", error);
  }
}

/src/app/app.module.ts

...
  providers: [
    PostService,
    {provide: ErrorHandler, useClass: AppErrorHandler}
  ],
...

How to use /src/app/post/post.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import 'rxjs/add/operator/catch'
import 'rxjs/add/observable/throw';

@Injectable()
export class PostService {

  private url = "https://jsonplaceholder.typicode.com/posts";

  constructor(private http: HttpClient) {
  }

  getPost(id): any {
    return this.http.get(this.url + "/" + id);
  }

  getPosts(): any {
    return this.http.get(this.url);
  }
}
import {Component, OnInit} from '@angular/core';
import {PostService} from "./post.service";

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html'
})
export class PostComponent implements OnInit {

  private postA: any;
  private postB: any;
  private posts: any[];

  constructor(private postService: PostService) {
  }

  ngOnInit() {

    this.postService.getPost(1).subscribe((response) => {
      this.postA = response;
    });

    this.postService.getPost(999).subscribe(
      (response) => {
        this.postB = response;
      }, (error) => {

        if (error.status === 404) {
          console.log('Some special case');
        }
        // pass error that is not special case, then GlobalHandler with catch this
        else throw error;
      });

    this.postService.getPosts().subscribe((response) => {
      this.posts = response;
    });

  }

}

as you see you don’t need to do anything if you don’t catch exception in the code, but if you add some special case like this additional if statment for 404 you have to re-throw error