I am working in http error handling. I have written error handling in each component which is not a good coding practice. So I have decided to write a common http error handling globally. I have searched for it, I have come across http-interceptor concept, I think there exists better way to handle the HTTP errors. What I have tried in each component is below Instead of that I need a global method. I already have http-interceptor file and the code is I am pasting below.
component.ts:
this.serviceName.methodName().catch(err => {
  console.log("Something went wrong with the request, please try again.");
  return Observable.throw(err.message.toUpperCase() || 'API_ERROR');
}).subscribe((res) => {
   console.log(res);
},
 error=>{
    this.openSnackBar('danger', "Something went wrong with the request, please try again.");
 });
http-interceptor:
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
        event => event instanceof HttpResponse ? 'succeeded' : '',
        err => 'failed'
    ))
 }
}
Please help. Thanks.


