Angular 2 - Error Handling


Advertisements

Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function.

Let’s see the code required for error handling. 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 link 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.

Useful Video Courses


Video

AngularJS Online Training

16 Lectures 1.5 hours

Anadi Sharma

Video

Angular 2 Online Training

28 Lectures 2.5 hours

Anadi Sharma

Video

Step By Step Angular For Beginnners

Best Seller

11 Lectures 7.5 hours

SHIVPRASAD KOIRALA

Video

Ionic & Angular JS: Principles Of Mobile and Web Development

16 Lectures 2.5 hours

Frahaan Hussain

Video

Angular 8 Full Stack Development With Spring Boot

Best Seller

69 Lectures 5 hours

Senol Atac

Video

JWT Role Based Authorization With Spring Boot And Angular 8

53 Lectures 3.5 hours

Senol Atac

Advertisements