简体   繁体   中英

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

  }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM