Angular - Catching error after all HTTP retry fail

2020-03-31 04:39发布

问题:

I am using Angular Service to get data from my API. I implemented retry feature in case of fetching data fails. Now i need to handle the error when all the retries wear out, but im not able to catch it.

Following is my code,

public getInfoAPI(category:string, id:string = "", page:string = "1", limit:string = "10"){
    var callURL : string = '';

    if(!!id.trim() && !isNaN(+id)) callURL = this.apiUrl+'/info/'+category+'/'+id;
    else callURL = this.apiUrl+'/info/'+category;

    return this.http.get(callURL,{
      params: new HttpParams()
        .set('page', page)
        .set('limit', limit)
    }).pipe(
      retryWhen(errors => errors.pipe(delay(1000), take(10), catchError(this.handleError)))//This will retry 10 times at 1000ms interval if data is not found
    );
  }
// Handle API errors
  handleError(error: HttpErrorResponse) {
    console.log("Who's there?");
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  };

I am succesfully able to retry 10 times with 1 sec delay, but when 10 retries complete, i want unable to catch the error.

Note:

I am new to Angular, so if you could suggest improvement in this call you're welcomed to do so.

回答1:

    return this.http.get(callURL,{
      params: new HttpParams()
        .set('page', page)
        .set('limit', limit)
    }).pipe(
      retryWhen(genericRetryStrategy({maxRetryAttempts: 10, scalingDuration: 1})),
      catchError(this.handleError)
    );

Where genericRetryStrategy is from this retrywhen resource

export const genericRetryStrategy = ({
  maxRetryAttempts = 3,
  scalingDuration = 1000,
  excludedStatusCodes = []
}: {
  maxRetryAttempts?: number,
  scalingDuration?: number,
  excludedStatusCodes?: number[]
} = {}) => (attempts: Observable<any>) => {
  return attempts.pipe(
    mergeMap((error, i) => {
      const retryAttempt = i + 1;
      // if maximum number of retries have been met
      // or response is a status code we don't wish to retry, throw error
      if (
        retryAttempt > maxRetryAttempts ||
        excludedStatusCodes.find(e => e === error.status)
      ) {
        return throwError(error);
      }
      console.log(
        `Attempt ${retryAttempt}: retrying in ${retryAttempt *
          scalingDuration}ms`
      );
      // retry after 1s, 2s, etc...
      return timer(retryAttempt * scalingDuration);
    }),
    finalize(() => console.log('We are done!'))
  );
};

Stackblitz



回答2:

Have you tried retry(10)? Then in the second subscribe callback you can handle the error:

return this.http.get(callURL,{
  params: new HttpParams()
    .set('page', page)
    .set('limit', limit)
}).pipe(
  retry(10)
).subscribe((res) => {}, (e) => {
  // handle error
});


回答3:

please try to change this:

}).pipe(
  retryWhen(errors => errors.pipe(delay(1000), take(10), catchError(this.handleError)))
);

to this: This might need a tweak for your own code but this approach works for me, the throwError will be catched as errors

}).pipe(
  mergeMap(x => {
    if(x == error) return throwError('Error!'); //tweak this for your error
    else return of(x);
  }),
  retryWhen(errors => errors.pipe(delay(1000), take(10))), 
  catchError(error => this.handleError(error)) // change here 
);

and make handle error return observable like:

handleError(err) {
  ..your code
  return of(err); //and NOT return throwError here
}


回答4:

According to the Errormessage you have CORS issue. You have to enable cors in your SLIM Backend http://www.slimframework.com/docs/v3/cookbook/enable-cors.html