Sub topic 3
Network Errors, 4xx and 5xx Responses
This chapter assumes you can make requests with HttpClient, read an HttpErrorResponse, and chain operators with pipe(). You will learn to sort every failed request into a category. Later chapters use that category to decide what to show the user and whether to retry.
Why the category matters
Every failed request is not the same kind of failure, and treating them alike causes real bugs.
- Retrying a
404three times only delays the same answer. - Telling the user "Server error" when their Wi-Fi dropped sends them to the wrong place.
- Showing a raw
503message to a customer exposes detail they cannot act on.
The status code is the main signal. Angular gives you one error type, HttpErrorResponse, for all of these cases, so you have to do the sorting yourself.
The three categories
| Category | Typical `status` | What happened | Usually worth retrying? |
|---|---|---|---|
| Network | `0` | The browser never received an HTTP response | Often yes |
| Client (4xx) | `400` to `499` | The server received the request and rejected it | Rarely |
| Server (5xx) | `500` to `599` | The server failed while handling a valid request | Sometimes |
The "usually worth retrying" column is a starting point. A later chapter on retry policy covers the exceptions in detail.
Network errors: status 0
When the browser cannot complete the request, Angular reports an HttpErrorResponse with status equal to 0. No HTTP response exists, so there is no real status code to report.
Status 0 covers several different causes:
- The device is offline, or DNS lookup failed.
- The server refused the connection or is not running.
- The request was blocked by CORS. The browser hides the response, and your code only sees
0. - The request was aborted, for example by navigation or an unsubscribe in some setups.
- A mixed-content or certificate problem stopped the request.
In these cases error.error is usually a ProgressEvent, not a useful message. Do not try to read a server message from it.
Client errors: 4xx
A 4xx status means the server understood the request and refused it. The fix is normally on the caller's side: change the request, sign in, or ask for something that exists.
| Status | Meaning | Typical reaction |
|---|---|---|
| `400` | Bad request | Fix the request. Show validation messages if the body has them |
| `401` | Not authenticated | Sign in again or refresh the token |
| `403` | Authenticated but not allowed | Show an "access denied" state. Do not retry |
| `404` | Resource not found | Show a "not found" state |
| `408` | Request timeout | Retry may help |
| `409` | Conflict with current state | Reload the data and let the user resolve it |
| `422` | Validation failed | Show field-level errors |
| `429` | Too many requests | Wait, then retry. Respect `Retry-After` |
Server errors: 5xx
A 5xx status means the request was probably valid but the server could not fulfil it.
| Status | Meaning | Retry? |
|---|---|---|
| `500` | Unexpected server failure | Maybe. Often a bug that will repeat |
| `501` | Not implemented | No |
| `502` | Bad gateway, an upstream server failed | Often yes |
| `503` | Service unavailable, usually temporary | Often yes |
| `504` | Gateway timeout | Often yes |
502, 503 and 504 come from proxies and load balancers and tend to be temporary. A plain 500 may be a permanent bug, so retrying it is a judgment call.
A decision flow
Writing a classifier
Put the sorting logic in one function so every service and interceptor uses the same rules.
import { HttpErrorResponse } from '@angular/common/http';
export type HttpFailureKind = 'network' | 'client' | 'server' | 'unknown';
export function classifyHttpError(error: unknown): HttpFailureKind {
if (!(error instanceof HttpErrorResponse)) {
return 'unknown';
}
if (error.status === 0) {
return 'network';
}
if (error.status >= 400 && error.status < 500) {
return 'client';
}
if (error.status >= 500 && error.status < 600) {
return 'server';
}
return 'unknown';
}The first check matters. Anything that is not an HttpErrorResponse falls into unknown. That includes a TimeoutError from the RxJS timeout operator and an exception thrown inside a map callback. Neither carries a status property, so reading one directly would give undefined.
The final unknown branch also catches a less obvious case. If the server returns 200 but the body cannot be parsed as the expected type, such as invalid JSON, Angular produces an HttpErrorResponse with status 200 and ok set to false. It fits none of the three categories, and your code should not treat it as a network problem.
Reading the response body safely
Servers often return details in the error body, such as { "message": "Email already used" }. The type of error.error depends on the situation, so check it before use.
import { HttpErrorResponse } from '@angular/common/http';
export function serverMessage(error: HttpErrorResponse): string | null {
const body: unknown = error.error;
if (typeof body === 'string' && body.length > 0) {
return body;
}
if (typeof body === 'object' && body !== null && 'message' in body) {
const message = (body as { message: unknown }).message;
return typeof message === 'string' ? message : null;
}
return null;
}Possible values of error.error:
- A parsed object, when the server sent JSON.
- A string, when the body was plain text or the response could not be parsed.
- A
ProgressEvent, when the request never completed. This is the status0case. null, when the body was empty.
Mapping categories to messages
With the classifier, one function can turn any failure into text for the user. This version covers the cases that most often need distinct wording.
import { HttpErrorResponse } from '@angular/common/http';
import { classifyHttpError } from './classify-http-error';
export function userMessage(error: unknown): string {
const kind = classifyHttpError(error);
if (kind === 'network') {
return 'We could not reach the server. Check your connection and try again.';
}
if (kind === 'client') {
const status = (error as HttpErrorResponse).status;
if (status === 401) return 'Please sign in to continue.';
if (status === 403) return 'You do not have permission to do that.';
if (status === 404) return 'We could not find what you asked for.';
if (status === 429) return 'Too many requests. Please wait a moment.';
return 'The request was not accepted. Check your input and try again.';
}
if (kind === 'server') {
return 'Something went wrong on our side. Please try again shortly.';
}
return 'An unexpected error occurred.';
}The cast (error as HttpErrorResponse) is safe here only because classifyHttpError returned 'client', which requires an HttpErrorResponse. If you prefer no casts, have the classifier return a result object that carries the status.
Reading Retry-After
Servers that return 429 or 503 may send a Retry-After header saying how many seconds to wait. Read it from the error's headers.
import { HttpErrorResponse } from '@angular/common/http';
export function retryAfterMs(error: HttpErrorResponse): number | null {
const value = error.headers.get('Retry-After');
if (value === null) {
return null;
}
const seconds = Number(value);
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : null;
}This handles only the numeric form. The header can also contain an HTTP date, which this function treats as absent by returning null. For cross-origin requests, the server must also list Retry-After in Access-Control-Expose-Headers. Without it, the browser hides the header and get returns null.
Common mistakes
- Checking
error.status >= 500without handling0first. Status0is less than 400, so it falls through every range check and ends up as a generic message. - Reading
error.messagefor display. It contains text such as "Http failure response for /api/users/1: 404 Not Found". That is meant for logs, not for users. - Assuming CORS failures look different from network failures. In the browser they are both status
0. Check the browser console to tell them apart during development. - Forgetting that errors inside
maportapare notHttpErrorResponseinstances.
Exercise
A request returns an HttpErrorResponse with status 0 and an error body that is a ProgressEvent. Which category is it, and why should you not read a message from error.error?
Show answer
It is a network error, because the browser received no HTTP response. The body is a ProgressEvent, not server content, so it holds no message to show. Use a fixed user-facing message instead.
Exercise
Extend classifyHttpError so a 429 response gets its own category, 'rate-limited'. What must change in the return type and in the order of the checks?
Show answer
Add 'rate-limited' to the HttpFailureKind union. Check error.status === 429 before the general 400 to 499 range check, because the range check would otherwise match first and return 'client'.