Sub topic 2
Reading an HttpErrorResponse
This chapter assumes you know TypeScript, can write a basic Angular service, understand RxJS observables and pipe(), and have made requests with HttpClient. It covers what HttpClient hands you when a request fails and how to read it safely. Later chapters build catchError and retry logic on top of this.
Where failures arrive
HttpClient methods return cold observables. A cold observable sends nothing until someone subscribes. When the request succeeds, the response body arrives on the next channel and the observable completes. When it fails, nothing arrives on next. The observable errors instead, and the error value is an HttpErrorResponse.
A response with a status outside 200 to 299 counts as a failure. A 404 or 500 is not delivered as a normal value, even though the server did answer. This holds if you pass observe: 'response' too. You always get the failure through the error channel.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ProbeService {
private http = inject(HttpClient);
probe(): void {
this.http.get('/api/does-not-exist').subscribe({
next: (body) => console.log('never reached on a 404', body),
error: (err: HttpErrorResponse) => console.log(err.status, err.statusText),
});
}
}The error callback is typed by you, not checked by the compiler. RxJS delivers unknown at runtime. Anything in the pipeline can throw something else, as the last section shows. Treat the annotation (err: HttpErrorResponse) as a promise you have to verify.
The shape of the object
HttpErrorResponse extends HttpResponseBase. These are the members you will use.
| Property | Type | Meaning | Column |
|---|---|---|---|
| `status` | `number` | HTTP status code. It is `0` when no HTTP response was received. | |
| `statusText` | `string` | The reason phrase, such as `Not Found`. For status `0` it is usually `Unknown Error`. | |
| `url` | `string \ | null` | The URL that was requested. It can be `null`. |
| `headers` | `HttpHeaders` | The response headers. It is empty if no response arrived. | |
| `error` | `any` | The payload. Its type depends on how the failure happened. | |
| `message` | `string` | A generated summary, such as `Http failure response for /api/users/1: 404 Not Found`. | |
| `ok` | `boolean` | Always `false` for an error response. | |
| `name` | `string` | Always `'HttpErrorResponse'`. |
Two of these need extra care. message is built by Angular for developers. It is fine in logs, but it is not text you should show to users. error has no single type, so the next section covers it on its own.
What `error.error` contains
The error property carries the underlying cause. What it holds depends on which of three situations occurred.
- The server responded with a failure status.
errorholds the response body, decoded according to the request'sresponseType. With the defaultjsontype, a JSON error body such as{"code":"USER_LOCKED","message":"Account locked"}arrives as an object. If the server sends plain text or HTML, such as an nginx error page, you get a string, because the JSON parse fails and Angular falls back to the raw text. - No response arrived.
statusis0. The cause might be a dropped connection, a DNS failure, a CORS block, or an aborted request. With the default XHR backend,erroris usually aProgressEvent. With the fetch backend (withFetch()), it is typically the error the browser'sfetchthrew. In both cases it is rarely useful to display. The browser deliberately hides the exact reason for cross-origin failures. - The response was successful but the body could not be parsed.
statusis the successful code, often200, andokis stillfalse.erroris an object with anerrorfield holding theSyntaxErrorand atextfield holding the raw body. ThemessagereadsHttp failure during parsing for ....
The third case surprises people. An error response can carry a status of 200. If you branch only on status >= 400, you will treat a broken body as success.
Classifying safely
A small helper keeps the branching in one place. It takes unknown, narrows with instanceof, and returns a plain description that the rest of your code can use without touching HttpErrorResponse directly.
import { HttpErrorResponse } from '@angular/common/http';
export interface ErrorDetails {
kind: 'network' | 'parse' | 'http' | 'unknown';
status: number | null;
serverMessage: string | null;
retryAfter: string | null;
}
export function readError(err: unknown): ErrorDetails {
if (!(err instanceof HttpErrorResponse)) {
return { kind: 'unknown', status: null, serverMessage: null, retryAfter: null };
}
if (err.status === 0) {
return { kind: 'network', status: 0, serverMessage: null, retryAfter: null };
}
if (err.status >= 200 && err.status < 300) {
return { kind: 'parse', status: err.status, serverMessage: null, retryAfter: null };
}
return {
kind: 'http',
status: err.status,
serverMessage: extractMessage(err.error),
retryAfter: err.headers.get('Retry-After'),
};
}
function extractMessage(body: unknown): string | null {
if (typeof body === 'string') {
return body.length > 0 && body.length < 200 ? body : null;
}
if (typeof body === 'object' && body !== null && 'message' in body) {
const message = (body as { message: unknown }).message;
return typeof message === 'string' ? message : null;
}
return null;
}Some choices in this helper are deliberate.
- Type checks on the body.
error.errorisany, so TypeScript will not stop you from writingerr.error.message. That line throws aTypeErrorwhen the body is a string ornull, and it throws inside your error handler, which hides the original problem. The helper checks the type first. - Length limit on string bodies. A string body is often a whole HTML error page. Returning only short strings keeps a gateway's markup out of your UI.
- Reading headers.
headers.get()returnsnullwhen the header is missing, and header names are case-insensitive. TheRetry-Afterheader can tell a retry policy how long to wait. You will use it in the backoff chapter.
You can call the helper from any error callback:
import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { readError } from './read-error';
@Injectable({ providedIn: 'root' })
export class OrdersService {
private http = inject(HttpClient);
load(): void {
this.http.get('/api/orders').subscribe({
error: (err: unknown) => {
const details = readError(err);
console.warn(`Orders failed (${details.kind}, status ${details.status})`);
},
});
}
}Common mistakes
- Reading
error.error.messagewithout checking. As shown above, this works for JSON bodies and throws for anything else. - Showing
err.messageto users. It contains the URL and status in developer wording. Map the status to your own text instead. - Trusting
url. Its type allowsnull. It can also differ from the URL you requested after a redirect, so use it for logging, not for matching requests to results. - Expecting
HttpErrorResponseeverywhere. The next section covers where it does not appear. - Using
instanceof ErrorEventas the network check. Older guides do this. Under XHR, network failures usually carry aProgressEvent, and under fetch they carry something else. Thestatus === 0test works for both backends.
When the error is not an HttpErrorResponse
HttpClient produces HttpErrorResponse for failures that happen in the HTTP layer. Other code in the same pipeline can throw other things:
- A
timeoutoperator throws aTimeoutErrorfrom RxJS. - An interceptor of your own might throw a plain
Error. - A
mapafter the request might throw aTypeErrorif the response had an unexpected shape.
Because of this, the instanceof check at the top of readError is required. Without it, your classifier would read status from an object that has none and silently fall through to the http branch with status as undefined.
Summary of what to read, and when
| Question | Where to look |
|---|---|
| Did the server answer at all? | `status === 0` means no. |
| Was the body unreadable on a successful status? | `status` in 200 to 299 with an `HttpErrorResponse`. |
| What did the server say went wrong? | `error`, after checking its type. |
| Should I wait before retrying? | `headers.get('Retry-After')`. |
| What do I log? | The whole error object plus `url`. |
The next chapter sorts these cases into network, client (4xx) and server (5xx) categories and decides what each one means for your application.
Exercise
A request to /api/report returns status 200, but the body is <html>Maintenance</html> and the request used the default JSON response type. What does the error callback receive, and how can your code recognize this case?
Show answer
The observable errors with an HttpErrorResponse whose status is 200 and whose ok is false. Its message begins with Http failure during parsing, and error is an object containing the SyntaxError and the raw text. Recognize it by checking for a status in the 200 to 299 range inside the error callback, as readError does when it returns kind parse.
Exercise
Why does readError check err instanceof HttpErrorResponse first, and what could go wrong if the check were removed?
Show answer
Other parts of the pipeline can throw values that are not HttpErrorResponse, such as a TimeoutError or a TypeError from a map callback. Without the check, err.status would be undefined. That value is not 0 and not in the 200 to 299 range, so the code would fall through and classify the failure as an HTTP error with an undefined status. Headers would also be missing, so err.headers.get would throw inside the error handler.