Sub topic 2
Reading an HttpErrorResponse
This chapter assumes you can write an Angular service that calls HttpClient, and that you know what an Observable is and how pipe() works. It covers the object that HttpClient gives you when a request fails.
Where the error object comes from
HttpClient methods return cold Observables. If the request fails, the Observable does not emit a value. It ends with an error notification, and the error is an HttpErrorResponse.
A request fails in two situations:
- The server answers with a status outside the 200 to 299 range, such as 404 or 503.
- No answer arrives at all. The network is down, the DNS lookup fails, the browser blocks the request for CORS reasons, or the request is aborted.
Both cases produce an HttpErrorResponse. The properties you read from it tell you which case you are in.
The properties that matter
| Property | Meaning |
|---|---|
| `status` | The HTTP status code. It is `0` when no HTTP response was received. |
| `statusText` | The reason phrase, such as `Not Found`. HTTP/2 and HTTP/3 servers often leave it empty. |
| `url` | The URL that was requested. It can be `null`. |
| `error` | The response body for server errors. For a failure with no response, it is a low-level browser event object. |
| `message` | A text summary that Angular builds for you. It is meant for logs. |
| `headers` | The response headers as an `HttpHeaders` object. |
| `ok` | Always `false` on an `HttpErrorResponse`. |
The error property has no fixed type. If the server sends JSON, you get the parsed object. If it sends plain text, you get a string. This is why code that reads error.error.message without checking can crash inside the error handler itself.
Telling the two cases apart
The reliable check is status === 0. Do not test error.error instanceof ErrorEvent. That pattern appears in older tutorials, but it does not catch every network failure.
import { HttpErrorResponse } from '@angular/common/http';
export function describeError(error: HttpErrorResponse): string {
if (error.status === 0) {
return 'Network error. The request never got a response.';
}
const body: unknown = error.error;
if (body !== null && typeof body === 'object' && 'message' in body) {
return String((body as { message: unknown }).message);
}
return `Server returned ${error.status} ${error.statusText}`;
}The function checks the status first. It then looks for a message field in the body, and it falls back to the status line if the body has none. Every access is guarded, so the function cannot throw on an unexpected body.
Common mistakes
- Assuming
erroris always the error you want.HttpClienthands you the wholeHttpErrorResponse. Your owncatchErrormay later turn it into a plainError, and the type changes at that point. - Reading
messagefor user text. The generatedmessagecontains the URL and status. It helps in logs but reads badly in a dialog. - Treating
status === 0as "offline". A CORS rejection and a request cancelled by a page navigation also give0. Treat it as "no response received". - Typing the handler parameter and trusting it. A
catchErrorcallback receivesunknownin practice. An error thrown elsewhere in the pipeline, such as a bug in amap, is not anHttpErrorResponse. Useerror instanceof HttpErrorResponsewhen the pipeline is long.
Using the function
Call describeError from a subscriber to see the result:
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject } from '@angular/core';
import { describeError } from './describe-error';
const http = inject(HttpClient);
http.get('/api/users/1').subscribe({
next: (user) => console.log(user),
error: (e: HttpErrorResponse) => console.warn(describeError(e)),
});The next chapter groups these statuses into network, 4xx and 5xx categories, because each group calls for a different response.
Exercise
A request returns an HttpErrorResponse with status 0. Name two possible causes, and say why you should not tell the user "the server is down".
Show answer
Possible causes are a lost network connection, a CORS rejection, a DNS failure, or an aborted request. Status 0 means no HTTP response was received at all, so you cannot know whether the server is down or the request never reached it.