English 中文(简体)
Angular 2 - Error Handling
  • 时间:2024-09-17

Angular 2 - Error Handpng


Previous Page Next Page  

Angular 2 apppcations have the option of error handpng. This is done by including the ReactJS catch pbrary and then using the catch function.

Let’s see the code required for error handpng. This code can be added on top of the chapter for CRUD operations using http.

In the product.service.ts file, enter the following code −

import { Injectable } from  @angular/core ; 
import { Http , Response } from  @angular/http ; 
import { Observable } from  rxjs/Observable ; 

import  rxjs/add/operator/map ; 
import  rxjs/add/operator/do ; 
import  rxjs/add/operator/catch ; 
import { IProduct } from  ./product ;  

@Injectable() 
export class ProductService { 
   private _producturl =  app/products.json ; 
   constructor(private _http: Http){}  

   getproducts(): Observable<IProduct[]> { 
      return this._http.get(this._producturl) 
      .map((response: Response) => <IProduct[]> response.json()) 
      .do(data => console.log(JSON.stringify(data))) 
      .catch(this.handleError); 
   }  
   
   private handleError(error: Response) { 
      console.error(error); 
      return Observable.throw(error.json().error()); 
   } 
}

    The catch function contains a pnk to the Error Handler function.

    In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue.

Now, whenever you get an error it will be redirected to the error console of the browser.

Advertisements