Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Angular 4 Error Handling and Logging!

How To Get and Log an Error in Angular 4?

Two types of errors -

1.     If the backend returns an unsuccessful response like - 404, 500 and so on

2.     If something goes wrong in the client side like -network error etc.


In the both cases - We are using HttpErrorResponse and return the useful information on what went wrong in this call!


Example –
http.get('/api/users')
.subscribe(data => {console.log(data);}, //Successful responses call the first callback.
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Error - ', err.error.message);
}else {
console.log('Error status - ${err.status}, and Error Detail - ${err.error}');
}
}
});

How To handle and retry the failed request due to Poor Network Connection in Angular 4?



In Angular 4, simply retry the request using RxJS operator called .retry (). It is automatically presubscribed to an Observable, thus reissuing the request when an error occurred!


Import RxJS for using retry () method-
import 'rxjs/add/operator/retry';

HTTP Observables for retry the failed request 
http.get('/api/users')
.retry(2) //Retry this request up to 2 times.
.subscribe(data => {console.log(data);}, //Successful responses call the first callback.
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Error - ', err.error.message);
}else {
console.log('Error status - ${err.status}, and Error Detail - ${err.error}');
}
}
});

References -

https://angular.io/guide/http

https://angular.io/api/common/http/HttpClient


I hope you are enjoying with this post! Please share with you friends. Thank you!!

Share the post

Angular 4 Error Handling and Logging!

×

Subscribe to Angular 2 Javascript Asp.net C# Sql Server Knockoutjs Angularjs Kendo Ui Html 5 Web Api Wpf Wcf Etc.

Get updates delivered right to your inbox!

Thank you for your subscription

×