Sub topic 1
HttpClient requests and where they can fail
Every error-handling decision in Angular starts with one question: at which stage did the request fail? This chapter maps the places where an HttpClient request can go wrong. Later chapters use that map for catchError, retries and interceptors.
Prerequisites
You should be comfortable with:
- TypeScript fundamentals, including interfaces and generics.
- Angular components and injectable services, including
inject(). - RxJS Observables and
pipe(). - Making a basic request with
HttpClient.
A request is a cold Observable
HttpClient methods such as get() return a cold Observable. A cold Observable does nothing until someone subscribes. Each subscription sends its own request.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`);
}
}Calling getUser(1) sends nothing. Two subscriptions to the same Observable send two requests. This matters for retries, because a retry resubscribes and therefore sends a new request.
One error channel, several causes
A request ends in one of two ways. It emits a value and completes, or it emits an error notification and stops. A failed request emits no next value. Every kind of failure arrives on the same error channel, so the cause is not obvious from the channel alone.
import { Component, OnInit, inject } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-user',
standalone: true,
template: `<p>{{ message }}</p>`,
})
export class UserComponent implements OnInit {
private users = inject(UserService);
message = 'Loading...';
ngOnInit(): void {
this.users.getUser(1).subscribe({
next: (user) => (this.message = `Hello, ${user.name}`),
error: (err) => (this.message = `Failed (status ${err.status})`),
});
}
}If you subscribe without an error callback, the error is not silently dropped. It is reported through Angular's ErrorHandler, which a later chapter covers.
Where a request can fail
A request passes through several stages. Each stage can fail in its own way.
The table lists each failure and how it shows up.
| Stage | Example cause | What you see |
|---|---|---|
| Interceptor | Your own code throws | The thrown error on the error channel |
| Network | Offline, DNS failure, CORS block, aborted request | `HttpErrorResponse` with `status` 0 |
| Server | Missing resource, validation failure, crash | `HttpErrorResponse` with a 4xx or 5xx `status` |
| Parsing | A 200 response with a body that is not valid JSON | `HttpErrorResponse` with `status` 200 and a parse `error` |
HttpClient treats any status outside the 2xx range as an error. That differs from fetch, which resolves normally for a 404 or 500.
Timeouts are not built in
HttpClient has no default timeout. A request to a server that accepts the connection but never replies stays pending until the browser gives up. A later chapter adds a timeout with RxJS.
What to take forward
- Nothing runs until you subscribe, and each subscription is a separate request.
- All failures use the error channel, so you inspect the error to find the cause.
- The error is usually an
HttpErrorResponse, but your own code can throw other types. Check the type before you readstatus. - Status 0 means no response reached the app.
The next chapter reads HttpErrorResponse in detail.
Exercise
A component calls this.http.get<User>('/api/users/1') and stores the result in a variable without subscribing or using any other operator. The server is offline. What request is sent, and what error does the user see?
Show answer
No request is sent and no error appears. The Observable is cold, so nothing runs until a subscription exists. Once something subscribes, the offline server produces an HttpErrorResponse with status 0.
Exercise
A server returns status 200 with the body <html>Maintenance</html> to a get<User>() call. Does HttpClient emit a value or an error?
Show answer
It emits an error. The default response type is JSON, so parsing fails and the result is an HttpErrorResponse with status 200 and the parse failure in its error property.