2

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.

1
  • 2
    Read the documentation, nothing explains interceptors better than it. Commented May 27, 2019 at 11:07

1 Answer 1

2

Try this:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        this.openSnackBar('danger', "Something went wrong with the request, please try again.");
      }
    ))
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, I already have an http-interceptor file, please check my answer again. Please suggest where to write the 'error' code from your answer in my http-interceptor file.
Getting error after adding your code like ERROR in src/app/services/common/httperror.interceptor.ts(15,13): error TS2345: Argument of type '(error: any) => void' is not assignable to parameter of type '() => void'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.