10

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

  }
}
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71

2 Answers2

6

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));
  })
 )
}
xinthose
  • 3,213
  • 3
  • 40
  • 59
stodi
  • 1,549
  • 13
  • 23
  • 1
    but lets say we need to call an API to get that new token, how do we do that inside catchError? – Collin Aug 15 '21 at 00:40
0

Even though this is not recommended, creating a success response from catchError can be done using HttpResponse class,

return next.handle(request)
    .pipe(
        catchError((error: HttpErrorResponse) => {
            return of(new HttpResponse({ body: {}, status: 0 }));
        })
    )
Midhun KM
  • 1,647
  • 1
  • 21
  • 31