Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for handling error in Angular2

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     } } 
like image 512
Vaibhav Avatar asked Feb 02 '17 09:02

Vaibhav


1 Answers

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.

like image 183
JEY Avatar answered Oct 14 '22 10:10

JEY