简体   繁体   中英

RxJS: filtering errors in catchError

I am developing an Angular frontend with ngRx store. I have an effect that will fetch orders from the backend API. The action is fetchOrders and if the fetch is succesful it will dispatch ordersFetched . If it is unsuccessful, the catchError will dispatch, after 10s wait, the fetchOrders action to retry the fetch.

@Effect()
fetchOrders$ = this.actions$.pipe(
  ofType(fetchOrders),
  switchMap(() => this.orderService.getOrders().pipe(
    map((orders) => {
      return ordersFetched({ orders });
    }),
    catchError((error) => timer(10000).pipe(
        tap(() => console.log(error)),
        tap(() => console.log('retry')),
        map(() => fetchOrders())
      )
    )
  )
  )
)

I would like to do the retry only when the error contains status code 591 (our own special error status code indicating the orders are not yet ready). What is the correct RxJs way to only catch errors with certain conditions (in this case status code 591)? I think there should be a filter operator somewhere before the timer operator but I am quite fresh with RxJs. If the status code is something else than 591 it should be unhandled error.

Bonus: can the actions$ be retried with RxJs operators rather than just dispatching the same action again?

I did this on Interceptor like this:

intercept(request: HttpRequest < any >, next: HttpHandler): Observable < any > {
     // Handle response
     return next.handle(request).pipe(
     map((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse) {
    // do something with response
  }
  return event;
}),
retryWhen((error) =>
  error.pipe(
    concatMap((error, count) => {
      if (error.status === 591) {
        if (count <= retryCount && request.method == 'GET') { return of(error); }

        // do something with Err
        return throwError(error);
      }
      return throwError(error);
    }),
    delay(retryWaitMilliSeconds)
  )),
catchError((error) => this._handleOtherStatusError(error, request, next))
);
}

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