Skip to content

Commit ffb03bf

Browse files
committed
retry interceptor added
1 parent 3f605cf commit ffb03bf

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

src/app/services/retry.interceptor.ts

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { HttpErrorResponse, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
2+
import { retry, timer } from 'rxjs';
3+
4+
const maxRetries = 3;
5+
const delayMs = 2000;
6+
7+
export const RetryInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: HttpHandlerFn) => {
8+
return next(req).pipe(
9+
retry({
10+
count: maxRetries,
11+
delay: (error: HttpErrorResponse, retryCount) => {
12+
if (error.status == 401) {
13+
console.log(req.url, ' : 401 retrying...', retryCount);
14+
return timer(delayMs);
15+
} else if (error.status >= 500) {
16+
console.log(req.url, ' : 500 retrying...', retryCount);
17+
return timer(delayMs);
18+
} else {
19+
console.log(`${req.url} : ${error.status} retrying... ${retryCount}`);
20+
return timer(delayMs);
21+
}
22+
throw error;
23+
},
24+
}),
25+
);
26+
};

src/main.ts

+2-7
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,13 @@ import { bootstrapApplication } from '@angular/platform-browser';
22
import { HttpHandlerFn, HttpRequest, provideHttpClient, withInterceptors } from '@angular/common/http';
33

44
import { AppComponent } from './app/app.component';
5+
import { RetryInterceptor } from './app/services/retry.interceptor';
56

67
function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) {
7-
/*
8-
const newReq = req.clone({
9-
headers: req.headers.set('new-Header', 'headerValue')
10-
});
11-
*/
12-
138
console.log('Interceptor: ', req);
149
return next(req);
1510
}
1611

1712
bootstrapApplication(AppComponent, {
18-
providers: [provideHttpClient(withInterceptors([loggingInterceptor]))],
13+
providers: [provideHttpClient(withInterceptors([loggingInterceptor, RetryInterceptor]))],
1914
}).catch(err => console.error(err));

0 commit comments

Comments
 (0)