Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Http Interceptor: catchError and return success

I have an Http Interceptor (Angular 7) that catches errors. Is it possible to catch the error and based on some contidition, returns a success instead of the error? My current code.

export class RequestInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      catchError( response => {
        if(someCondition) {
           //return something that won't throw an error
        }
        return of(response)
      })
    )

  }
}
like image 790
Christian Benseler Avatar asked Feb 07 '19 13:02

Christian Benseler


People also ask

Can I have multiple HTTP interceptors in angular?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.

What does HTTP interceptor do in angular?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.

Can we have multiple interceptors?

Yes, you can have multiple angular interceptors by changing the value of multi to true.

What is Httperrorresponse?

HttpErrorResponselink A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.


1 Answers

You need to return an Observable<HttpEvent<any>> object. You can achieve that by making another request using next.handle(newReq)

For example, if you want to add a Bearer authorization header if the error is 401, you can do like that

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

return next.handle(request).pipe(
  catchError( response => {
    if(response.status === 401) {
       return next.handle(request.clone({
         setHeaders: { "Authorization": `Bearer ${token}` }
       }));
    }
    return throwError(() => new Error(response));
  })
 )
}
like image 158
stodi Avatar answered Oct 10 '22 23:10

stodi