Christian Benseler
Christian Benseler

Reputation: 8065

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

  }
}

Upvotes: 11

Views: 14734

Answers (2)

stodi
stodi

Reputation: 1651

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

Upvotes: 6

Midhun KM
Midhun KM

Reputation: 1717

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

Upvotes: 0

Related Questions