python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
Angular 4 Error handling

Angular 4 Error Handling - Logging, Retry Request and HttpCache!

What Happens If the Request fails on the Server Due to Poor Network Connection?
HttpClient will return an error instead of a successful response.

Example - Add an error handler to handle the errors
http.get('/api/users')
  .subscribe(data => {console.log(data);}, //Successful responses call the first callback.
      err => {console.log('Got error!'); //Errors - Something went wrong!
});

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}');
        }
      }
});

How to implement HttpCache in Angular 4?

We can use Http interceptors to implement caching.

@Injectable()
export class CachingInterceptor implements HttpInterceptor {
  constructor(private cache: HttpCache) {}
 
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Cache all GET requests and Skip other requist like POST, PUT etc.
    if (req.method !== 'GET') {
       return next.handle(req);
    }
 
    // Cached Response for all exists GET requests.
    const cachedResponse = this.cache.get(req);

    //If cached response is exists.
    if (cachedResponse) {
       return Observable.of(cachedResponse);
    }else{
       //If cached response is not exists.
       return next.handle(req).do(event => {
          if (event instanceof HttpResponse) {
         this.cache.put(req, event);// Update the cache.
          }
      });
    }
  }
}

References -

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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions