angularreactjsrxjsretrywhen

Throw error after the retry fails with Angular http.get


I'm trying to implement Angular5 http.get with retry. I wrote

http.get<any>('/api/study').retryWhen(
    (errors: Observable<any>):Observable<any> => {
        return errors.flatMap((error: any) => {
            if (error.status  == 500) {
                return Observable.of(error.status).delay(1000);
            }
            return Observable.throw(error);
        }).take(5);
    });

This will keep retrying up to 5 times if it gets error 500. However, if it gets 5 failures in a row, then it returns success (with null data). I don't want that. Instead I want it to throw the last error.

I tried to put .concat(Observable.throw({})) after the take(), and that works, but it does not give me any information, such as the status code of the most recent error.

How can I get the most recent error after the last retry fails?


Solution

  • You don't need to use take(5) to count the failed attempts and count it yourself using a local variable.

    For example you could do this:

    http.get<any>('/api/study').retryWhen((errors: Observable<any>) => {
        let errors = 0;
    
        return errors.flatMap((error: any) => {
            if (errors++ < 5 && error.status  == 500) {
                return Observable.of(error.status).delay(1000);
            }
            return Observable.throw(error);
        });
    });