Sub topic 10
Centralized error handling and retry
This chapter assumes you can write and register a functional interceptor with withInterceptors. It also assumes you know pipe, tap and catchError from RxJS. Here you will move error handling out of individual components and into interceptors. You will also add a retry policy that is safe for the requests it touches.
Why handle errors in one place
Without an interceptor, each subscribe or catchError call repeats the same checks: network down, 500 from the server, 403 for a forbidden resource. These copies drift apart. One component shows a message, another swallows the error, and a third forgets the case entirely.
An interceptor sees every failed response before the caller does. It can log the failure, translate it, or retry the request. It must then either recover or pass the error on, so callers can still react.
The shape of an HTTP failure
When a request fails, the observable returned by next(req) errors with an HttpErrorResponse. Its useful fields are:
status: the HTTP status code, or0when no response arrived (network down, CORS block, request aborted).statusTextandmessage: human-readable text.error: the response body, or a browserProgressEventwhenstatusis0.url: the URL that failed.
The status === 0 case differs from the others because the server never answered. Treat it separately.
A minimal error interceptor
This interceptor observes failures and rethrows them:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 0) {
console.error('Network error', error.error);
} else {
console.error(`Server returned ${error.status}`, error.message);
}
return throwError(() => error);
}),
);
};The last line matters most. catchError replaces the failed stream with whatever observable you return. If you return EMPTY or of(null), the caller sees a successful completion or a null value and never learns that the request failed. Return throwError(() => error) unless you truly mean to recover.
Handling specific statuses
A mapping function keeps the policy readable and easy to test. This version turns an error into a user-facing message and sends a 403 to a "forbidden" page:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
function messageFor(error: HttpErrorResponse): string {
if (error.status === 0) {
return 'Cannot reach the server. Check your connection.';
}
if (error.status === 404) {
return 'The requested item was not found.';
}
if (error.status >= 500) {
return 'The server had a problem. Try again later.';
}
return 'The request could not be completed.';
}
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
console.error(messageFor(error), error.url);
if (error.status === 403) {
router.navigate(['/forbidden']);
}
return throwError(() => error);
}),
);
};inject(Router) runs at the top of the interceptor function, which is inside the injection context. Calling inject later, inside the catchError callback, would throw, because by then the context is gone.
Do not handle 401 here yet. A 401 often means "refresh the token and replay the request", which is a larger pattern covered in a later chapter.
Adding retry
Some failures are temporary: a dropped connection, a gateway restarting, a brief overload. Retrying these a couple of times can hide them from the user. RxJS provides retry, which resubscribes to the source observable after an error. For next(req), resubscribing sends the request again.
A retry interceptor needs three decisions:
- Which methods. Only retry requests that are safe to repeat.
- Which errors. Only retry failures that might succeed next time.
- How long to wait. Retrying immediately tends to hit the same problem.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'];
const RETRYABLE_STATUSES = [0, 502, 503, 504];
export const retryInterceptor: HttpInterceptorFn = (req, next) => {
if (!RETRYABLE_METHODS.includes(req.method)) {
return next(req);
}
return next(req).pipe(
retry({
count: 2,
delay: (error, retryCount) => {
const retryable =
error instanceof HttpErrorResponse &&
RETRYABLE_STATUSES.includes(error.status);
return retryable ? timer(retryCount * 500) : throwError(() => error);
},
}),
);
};How it works:
count: 2allows at most two retries, so three attempts in total.- The
delayfunction runs after each error. It receives the error and the retry number, starting at 1. - Returning
timer(...)waits, then retries. The wait grows with each attempt: 500 ms, then 1000 ms. - Returning
throwError(...)stops retrying and sends the error downstream at once. A 404 or 400 will not change on a second try, so those fail immediately.
Why only some methods
A GET that runs twice returns the same data twice. A POST that runs twice can create two orders or charge a card twice. A network error does not tell you whether the server processed the request before the connection dropped. Restrict automatic retry to idempotent methods (those where repeating the call has the same effect as making it once), unless your API supports idempotency keys.
Order decides what you see
Retry and error handling interact through interceptor order. A retry resubscribes to next(req), which re-runs every interceptor that comes after the retry interceptor in the array. Interceptors before it run once.
Compare two orders:
| Array order | Effect |
|---|---|
| `[retryInterceptor, errorInterceptor]` | The error interceptor runs on every attempt, so one flaky request can log three errors. |
| `[errorInterceptor, retryInterceptor]` | The error interceptor sees only the final failure, after retries are exhausted. |
The second order is usually what you want. Put the error interceptor first (outermost) and retry last (closest to the backend):
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { errorInterceptor } from './app/error.interceptor';
import { authInterceptor } from './app/auth.interceptor';
import { retryInterceptor } from './app/retry.interceptor';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptors([errorInterceptor, authInterceptor, retryInterceptor]),
),
],
});Here authInterceptor sits before retryInterceptor, so it attaches the token once. Retried attempts reuse the already modified request instead of running the auth logic again.
Letting a request opt out
Some calls should not be retried or should fail silently, for example a background health check. Use an HttpContextToken as in the earlier chapter on HttpContext. Declare a token and read it in the interceptor:
import { HttpContextToken } from '@angular/common/http';
export const NO_RETRY = new HttpContextToken<boolean>(() => false);Then add if (req.context.get(NO_RETRY)) { return next(req); } at the top of retryInterceptor. The caller passes { context: new HttpContext().set(NO_RETRY, true) } in the request options. This keeps the policy in one place while allowing exceptions without custom headers.
Edge cases and pitfalls
- Swallowed errors. Returning
EMPTYorof(...)fromcatchErrorhides the failure from callers. Rethrow unless the interceptor deliberately supplies a fallback value. - Non-HTTP errors.
catchErroralso catches errors thrown by interceptors later in the chain, such as a bug in your own code. Checkerror instanceof HttpErrorResponsebefore readingstatus. - Retrying after a timeout. If you also use a
timeoutoperator, order it relative toretryon purpose. Atimeoutplaced beforeretryin the pipe applies to each attempt, while one placed after applies to all attempts combined. - Retry storms. If many clients retry on the same schedule when a server recovers, they all hit it at once. Adding random jitter to the delay spreads them out.
- Duplicate notifications. If both an interceptor and a component show an error message, the user sees two. Decide who owns user-facing messages. A common split is that the interceptor logs and handles global cases (403, network down), and components handle errors that need page-specific wording.
- Streaming and progress events. With
reportProgress: true, the stream emits several events. A retry restarts the whole request, so the progress bar starts again.
Exercise
A teammate writes [retryInterceptor, errorInterceptor] and sees three "Server returned 503" log lines for one failing GET (two retries, then failure). What change to the array gives one log line, and why? Also, why should the retry interceptor skip POST requests?
Show answer
Change the order to [errorInterceptor, retryInterceptor]. A retry resubscribes to next(req), which re-runs the interceptors after it in the array. With the error interceptor first, it sits outside the retry, so it only sees the final error after all attempts are used. POST is not idempotent, and a network failure does not show whether the server already processed the request. Repeating it could create duplicate records or charges.