I have a basic HttpInterceptor in which I am using the rxjs retryWhen in order to retry a certain number of times if there are service failures. If the service call has reached the maximum retry amount then I would like to feed this back to the method that originally instigated the service call.
My question is, how can I return control back to the original instigator of the http call? I need to do this in order to centralise control of handling retries in a single place (the interceptor) and I would like to be able to call back to a success/failure method in the calling function.
My problem is that the error is swallowed by the global error handler and nothing gets passed back to my caller.
Example:
this.MyServiceCall()
.pipe(
map((result) => {
console.log('this is called when the service returns success');
}),
)
// If there is an error, then how can I show it?
})
}
export class HttpRetryInterceptorService implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
retryWhen(errors => errors
.pipe(
concatMap((err:HttpErrorResponse, count) => iif(
() => (count < 3),
of(err).pipe(
map(()=>{
console.log(count.toString())
}),
delay((2 + Math.random()) ** count * 200)),
throwError(err)
))
))
);
}
}
Try using catchError()
this.MyServiceCall()
.pipe(
map((result) => {
console.log('this is called when the service returns success');
}),
catchError((error) => {
// Do something and return either an observable or rethrow the error
return throwError(error);
})
);
https://www.learnrxjs.io/operators/error_handling/catch.html