Search code examples
javascriptangularrxjshttp-status-codes

Angular retryWhen with condition statuscode


I'm having a question with retryWhen.

I am doing a barcode scan app, the requirement is when the status code is 500, we will retry the request, if 400 then push that barcode into an array (to list the barcode with error 400).

I need to run .retryWhen with status code as requirement as above. My code is now like this, but it always retry when there is an error and skip the .subcribe, which I need to handel error 400, I just need to retry when it's status code 500, with 400 then push that barcode into the array.

let modelItem = {
   ...
};
this._pickAppSv.updateTicketStatus(modelItem, !endWave)
 .retryWhen((obs) => { // Retry when error status is 500, 10 times
  return obs
   .mergeMap(error => (error.status === 500) ? Observable.throw(error) : Observable.of(error))
   .take(9);
 })
 .subscribe(
  (resp: any) => {
   ...
  },
  (err) => {
   if (err.message === 'Bad Request') { // error 400
    this.errorList.push(modelItem);
   }
  }
 );

I searched a lot but there did not seem to be a solution. Really appreciate your help.


Solution

  • You can do something like this

    this._pickAppSv.updateTicketStatus(modelItem, !endWave).pipe(
                retryWhen(obs => {
                    return obs.pipe(
                        mergeMap((response) => {
                            if (response.status === 500) {
                                return of(response).pipe(
                                    delay(2000),
                                    take(9)
                                );
                            }
                            if (response.status == 404) {
                              //do something
                              throw({error: response});
                            }
    
                            return throwError({error: "Unknown error for asynchronous function:" + response});
                        }),
                    );
                })
            ).subscribe({
              //do something
            });