Best practice for handling error in Angular2

Vaibhav picture Vaibhav · Feb 2, 2017 · Viewed 28.9k times · Source

Hi i am trying to receive error sent from catch block (service). in multiple components i need to show a popup with the error message displayed. please let me know how to create a generic method and call it inside service block. Like what i am doing now with "showErrorPage()".

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class DataService {
    private reqData = {};
    private url: string;
    constructor(private http: Http) {
    }

    getResult(searchObject: {}): Observable<Response> {
        // some logic
        return this.http.post(<my url>, <data to be sent>)

        .map((response: Response) => {
            return response;
        })
        .catch((error: any) => {
            if (error.status === 302 || error.status === "302" ) {
                // do some thing
            }
            else {
              return Observable.throw(new Error(error.status));
            }
        });
    }
}

And in my component i am calling it like

import { Component,EventEmitter, Output, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
// importing DataService ';

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

export class AComp implements OnInit {
    constructor(
        private dataService: DataService
    ){

    }

    ngOnInit() {
      this.dataService.getResult(<url>, <params>)
      .subscribe(
         response => {
             // doing logic with responce
         }
          ,
          error => {
            this.showErrorPage();
         }
      )

    }

    showErrorPage(): void {
      // displaying error in popup
    }
}

Answer

JEY picture JEY · Feb 2, 2017

According to the angular style guide

The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers.

Your implementation seems to be the correct one.

Furthermore the http client documentation provides the same implementation.