There are following ways to handle the errors in Angular JS
1. ReactJS catch library and then using the catch function
2. Using the ErrorHandler class
ReactJS catch library and then using the catch function:-
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
return this._http.get(this._producturl)
.map((response: Response) =>
.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.
Using the ErrorHandler class
import { ErrorHandler, Injectable} from '@angular/core';
@Injectable()
export class MyErrorHandler implements ErrorHandler {
constructor() { }
handleError(error) {
console.log('Hio')
// IMPORTANT: Rethrow the error otherwise it gets swallowed
throw error;
}
}
Module
import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { GlobalErrorHandler } from './error-handler';
import { ServicesModule } from './services';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
providers: [
{
provide: ErrorHandler,
useClass: GlobalErrorHandler
}
]
})
export class AppModule { }
Now we if we just do throw new Error('Im errorn') anywhere in our application, we will see our cool console message.
While using ErrorHandler there is no need to use this class in Every component. Once you have implemented it with ErroHandler and decorated it with Injectable. Then all error will caught in handleError function.
No comments:
Post a Comment