Sub topic 5
Showing error state to users
This chapter covers what happens after catchError has caught a failure: how the failure reaches the person using your app. It assumes you can read TypeScript, build a standalone Angular component, use signals at a basic level, and call HttpClient with pipe(). You should also know how to tell network errors from 4xx and 5xx responses, and how catchError turns an error into a value or a new error.
Why error state needs its own design
A caught error is only half handled. If catchError logs to the console and returns EMPTY, the user sees a spinner that never ends or a blank page. The user cannot tell whether the app is still working, whether they did something wrong, or whether trying again would help.
Each request that matters to the user should have three visible states:
- Loading: the request is in flight.
- Success: the data arrived.
- Error: the request failed, and the screen says so.
You should be able to tell from the screen alone which state you are in. The sections below model these states as data and turn status codes into messages. They also separate errors that block a screen from errors that only need a short notice.
The diagram below shows the states and the transitions between them.
Model the state as data
A discriminated union makes impossible combinations unrepresentable. With separate loading, data and error fields you can end up with loading: true and an error message at the same time. A union with a status field allows only one state at once.
export type LoadState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };A small function wraps any observable into a stream of these states. It emits loading first, then success for each value, and converts a failure into an error state instead of letting the error terminate the stream.
import { HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, map, of, startWith } from 'rxjs';
export type LoadState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
export function toUserMessage(error: unknown): string {
if (!(error instanceof HttpErrorResponse)) {
return 'Something went wrong. Please try again.';
}
switch (error.status) {
case 0:
return 'Cannot reach the server. Check your connection and try again.';
case 401:
return 'Your session has expired. Please sign in again.';
case 403:
return 'You do not have permission to see this.';
case 404:
return 'We could not find what you asked for.';
case 429:
return 'Too many requests. Please wait a moment and try again.';
default:
return error.status >= 500
? 'The server had a problem. Please try again shortly.'
: 'The request could not be completed.';
}
}
export function loadState<T>(source$: Observable<T>): Observable<LoadState<T>> {
return source$.pipe(
map((data): LoadState<T> => ({ status: 'success', data })),
startWith<LoadState<T>>({ status: 'loading' }),
catchError((error: unknown) =>
of<LoadState<T>>({ status: 'error', message: toUserMessage(error) })
)
);
}Because catchError sits at the end of the pipe, the observable completes after emitting the error state. A retry means subscribing again, which the component below does.
Write messages for people, not for developers
toUserMessage maps status codes to sentences. Three rules keep those sentences useful:
- Say what happened in the user's terms. "Cannot reach the server" is better than "Http failure response for /api/users/1: 0 Unknown Error".
- Say what the user can do. Check the connection, wait, sign in again, or contact support.
- Do not show raw server text by default.
HttpErrorResponse.messagecontains the request URL.error.errorcan contain stack traces or internal identifiers. Log these for developers and keep them off the screen.
The table shows how each category usually maps to a user-facing choice.
| Failure | Typical message | Offer retry? |
|---|---|---|
| Status 0 (network) | Cannot reach the server | Yes |
| 400 or 422 (validation) | Show field-level messages from the API | No, the user must fix the input |
| 401 | Session expired, sign in again | No, send to sign-in |
| 403 | No permission | No |
| 404 | Not found | No |
| 429 | Too many requests | Yes, after a pause |
| 5xx | Server problem | Yes |
A 4xx response means the request itself is wrong, so repeating it will give the same result. Showing "Try again" there misleads the user. Which failures are safe to retry automatically is the subject of a later chapter. Here the point is only that the visible retry button should follow the same logic.
Render the state in a component
The component below calls an endpoint, stores the latest LoadState in a signal, and derives three small signals for the template. It uses computed signals instead of narrowing inside the template, which keeps the template simple and type-safe.
import { HttpClient } from '@angular/common/http';
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { LoadState, loadState } from './load-state';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-profile',
standalone: true,
template: `
@if (isLoading()) {
<p role="status">Loading profile...</p>
}
@if (errorMessage(); as message) {
<div role="alert">
<p>{{ message }}</p>
<button type="button" (click)="load()">Try again</button>
</div>
}
@if (user(); as u) {
<h2>{{ u.name }}</h2>
}
`,
})
export class UserProfileComponent {
private http = inject(HttpClient);
private destroyRef = inject(DestroyRef);
readonly state = signal<LoadState<User>>({ status: 'loading' });
readonly isLoading = computed(() => this.state().status === 'loading');
readonly errorMessage = computed(() => {
const s = this.state();
return s.status === 'error' ? s.message : null;
});
readonly user = computed(() => {
const s = this.state();
return s.status === 'success' ? s.data : null;
});
constructor() {
this.load();
}
load(): void {
loadState(this.http.get<User>('/api/users/1'))
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((s) => this.state.set(s));
}
}Several details matter here:
load()emitsloadingsynchronously throughstartWith. A click on "Try again" immediately hides the error and shows the loading indicator, so the user gets feedback and cannot click twice during one attempt.role="status"androle="alert"tell screen readers to announce the loading and error text. An error that appears silently is invisible to users of assistive technology.takeUntilDestroyedunsubscribes when the component is destroyed. Without it, a slow response could write into a signal of a component that is gone.- Clicking "Try again" twice quickly cannot create two overlapping requests in practice, because the error block disappears on the first click. If you trigger
load()from other places, switch to a single stream withswitchMapso an older response cannot overwrite a newer one.
If your service wraps failures in a plain Error, as the catchError example earlier in this tutorial did, toUserMessage falls into its default branch and loses the status code. Either let the HttpErrorResponse pass through to the component, or throw a custom error class that carries status. The chapters on retry and interceptors rely on the original HttpErrorResponse being available.
Blocking errors and non-blocking errors
The load-state pattern fits data that a screen cannot work without. Other failures should not replace the screen. A failed "save" on a form, a failed "like" button or a background refresh should leave the page in place and show a short notice.
For these, use a notification service that holds a signal of messages, and call it from catchError.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class NotificationService {
private readonly _messages = signal<string[]>([]);
readonly messages = this._messages.asReadonly();
error(message: string): void {
this._messages.update((list) => [...list, message]);
}
dismiss(index: number): void {
this._messages.update((list) => list.filter((_, i) => i !== index));
}
}A component that saves data then reports the failure and keeps the stream alive:
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { EMPTY, catchError } from 'rxjs';
import { NotificationService } from './notification.service';
import { toUserMessage } from './load-state';
@Component({
selector: 'app-save-button',
standalone: true,
template: `<button type="button" (click)="save()">Save</button>`,
})
export class SaveButtonComponent {
private http = inject(HttpClient);
private notifications = inject(NotificationService);
save(): void {
this.http
.put('/api/users/1', { name: 'Ada' })
.pipe(
catchError((error: unknown) => {
this.notifications.error(toUserMessage(error));
return EMPTY;
})
)
.subscribe(() => {
// Runs only on success because EMPTY emits no value.
});
}
}Returning EMPTY is safe here because nothing downstream waits for a value. If the caller needs to know about the failure, for example to keep a form in the dirty state, rethrow with throwError instead.
A separate component, rendered once near the top of your layout, reads messages() and displays the notices. Give the container role="alert" or aria-live="polite", and add a dismiss button so notices do not pile up.
Choosing between the two patterns
Use these criteria:
- Does the screen make sense without this data? If not, use the load state and replace the content with the error block.
- Did the user trigger the action? If so, a notice next to the action is clearer than a blank page.
- Can the user recover on their own? If so, include a retry button or a concrete next step.
- Is it a background refresh? Keep the old data on screen and show a small "could not refresh" notice. Replacing good data with an error state makes the app look worse than it is.
Avoid showing the same failure twice, for example an inline error block plus a toast. Pick one place for each failure.
Common mistakes
- Swallowing errors with
EMPTYin a load path. The user sees nothing, and the loading indicator may never clear. - Displaying
error.messagedirectly. It leaks URLs and reads like a log line. - Offering "Try again" for a 404 or a validation error. The result will not change.
- Forgetting that
catchErrorends the stream. After the error state is emitted, the observable is complete. Retrying means a new subscription, not waiting for another value. - No announcement for assistive technology. Use
role="alert"for errors.
Errors that no component handled still need a destination. The chapter on the global ErrorHandler covers that.
Exercise
A dashboard refreshes its list of orders every 30 seconds. One refresh fails with a 503. Should you replace the list with a full-screen error block? Explain which pattern fits and what the user should see.
Show answer
No. The list is already on screen, so replacing it with an error block would discard good data because of one failed background refresh. Keep the old list and show a short non-blocking notice such as "Could not refresh orders. Showing the last loaded data." through a notification service. Because 503 is a transient server error, the next scheduled refresh acts as the retry, so a manual "Try again" button is optional. Use the load-state error block only for the initial load, when there is no data to show.
Exercise
In loadState, why is catchError placed after startWith and map rather than before them?
Show answer
catchError must see the errors from the source observable, and it must return an observable of LoadState values. Placed last, it catches the error from the source (which passes through map and startWith unchanged) and replaces it with an error state. The loading state has already been emitted by startWith at subscription, so the user sees loading first and error afterwards. Placing catchError before map would make it return a value of the wrong type, because the fallback would then be wrapped in a success state by map.