Sub topic 8
Handling failures
This chapter assumes you can write a basic resource() with a params function and a loader, and that you know how signal, computed and effect work. It also assumes you know that fetch returns a Promise. Earlier chapters covered the status signals. Here you will use them to deal with things that go wrong.
What counts as a failure
A resource enters the error status when its loader fails in one of two ways:
- The loader function throws an exception.
- The Promise the loader returns rejects.
Because an async function turns a thrown exception into a rejected Promise, both cases look the same to the resource.
The rule is simple, but one detail catches many people. fetch rejects only when the request itself cannot complete, for example when the network is down or the request is blocked. A response with status 404 or 500 is a successful fetch. If you do not check res.ok yourself, the loader returns the error page's body as if it were data, and the resource ends up in resolved.
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`); // turns a 4xx/5xx into a resource error
return (await res.json()) as User;
}The throw line is the whole bridge between HTTP errors and resource errors. httpResource does this for you, because Angular's HTTP stack already treats non-2xx responses as errors.
What the resource exposes when it fails
When the loader fails, the resource changes in these ways:
status()becomes'error'.error()holds whatever the loader threw.isLoading()becomesfalse.hasValue()becomesfalse.
The type of error() depends on your Angular version. In some releases it is unknown, and in others it is Error | undefined. In both cases, treat the value as untrusted and narrow it with instanceof before reading properties such as status.
Reading value() while the resource is in the error state is a trap. In recent Angular versions value() throws in that state instead of returning undefined. Check error() first, or guard with hasValue(), which is always safe to call. In a template, put the error branch first.
@if (user.error()) {
<p>Could not load the user.</p>
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ user.value()?.name }}</p>
}If you put the value() read before the error() check, a failed load can raise an exception during rendering, which is harder to debug than a missing message.
The error lifecycle
An error is not permanent. The resource leaves the error state whenever it starts another load, and there are two triggers for that:
- A signal read inside
paramschanges. The resource starts a new load, and the old error disappears. - You call
reload(). The loader runs again with the same params.
The diagram simplifies one point. The exact status name after a retry (loading or reloading) depends on whether the resource still has a previous value. If you branch on isLoading(), which covers both names, you do not need to care about the difference.
Also remember that results from superseded requests are discarded. If the user switches from id 1 to id 2 while request 1 is still running, the resource aborts request 1 and ignores its outcome. An abort of an obsolete request does not show up as an error.
Turning errors into useful messages
A generic "Something went wrong" is easy to write but poor for users. A 404 means retrying is pointless. A 503 or a dropped connection might succeed on a second attempt. You can express that by throwing a small error class that carries the HTTP status, then deriving the message from it with computed.
import { Component, computed, effect, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
class HttpFailure extends Error {
constructor(readonly status: number) {
super(`HTTP ${status}`);
this.name = 'HttpFailure';
}
}
@Component({
selector: 'app-user-card',
template: `
@if (user.error()) {
<p role="alert">{{ message() }}</p>
@if (canRetry()) {
<button (click)="user.reload()">Try again</button>
}
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else {
<p>{{ user.value()?.name }}</p>
}
`,
})
export class UserCardComponent {
readonly userId = signal(1);
readonly user = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const res = await fetch(`/api/users/${params.id}`, { signal: abortSignal });
if (!res.ok) throw new HttpFailure(res.status);
return (await res.json()) as User;
},
});
readonly message = computed(() => {
const err = this.user.error();
if (err instanceof HttpFailure) {
if (err.status === 404) return 'That user does not exist.';
if (err.status >= 500) return 'The server had a problem. Please try again.';
}
return 'Could not load the user. Check your connection.';
});
readonly canRetry = computed(() => {
const err = this.user.error();
return !(err instanceof HttpFailure && err.status === 404);
});
constructor() {
effect(() => {
const err = this.user.error();
if (err) console.error('User load failed', err);
});
}
}A few details in this example are worth noting:
- The loader throws
HttpFailureonly for HTTP responses. A network failure fromfetcharrives as a plainTypeError, which falls through to the generic message. messageandcanRetryarecomputedsignals, so they update by themselves when the error changes. The template stays free of logic.- The
effectreports the error once per change. Doing the logging in the template instead would re-run it on every change detection pass.
Keeping old data on screen after a failed refresh
When a reload() fails, the resource switches to error. In the template above, the @if (user.error()) branch then replaces the user's name with an error message, even though you had good data a moment ago. For a first load that is right. For a background refresh it can feel harsh.
You have two options:
- Accept the replacement, which is simple and unambiguous.
- Show the error as a banner and keep rendering the last known data. For this, keep a copy of the last good value yourself, for example in a
linkedSignalor a plain signal updated by aneffect, and render that copy.
Do not rely on value() to keep the old data after a failure, because it may throw in the error state. Use hasValue() if you need to ask whether a value is available.
Errors with rxResource and httpResource
The same rules hold for the other two kinds of resource:
- With
rxResource, an Observable that emits anerrornotification puts the resource in theerrorstate. AcatchErroroperator inside the stream can turn a failure into a fallback value. In that case the resource never sees an error, so use it only when a fallback is the behavior you want. - With
httpResource, any non-2xx response or network failure sets the error state.error()holds anHttpErrorResponse, so you can readstatusafter narrowing withinstanceof HttpErrorResponse, and you do not need a custom class.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Not checking `res.ok` | HTTP errors resolve as if they were data | Throw when `!res.ok` |
| Reading `value()` before `error()` | Possible exception while rendering | Check `error()` first, or use `hasValue()` |
| Assuming `error()` is an `Error` | Type errors or crashes on `err.message` | Narrow with `instanceof` |
| Retrying 4xx errors automatically | Repeated pointless requests | Offer retry only for network and 5xx failures |
| Logging errors inside the template | Duplicate log lines | Log from an `effect` |
Exercise
A loader calls fetch('/api/items') and returns await res.json() without any other checks. The server answers with status 500 and the body {"message":"boom"}. What status does the resource report, and what single line fixes the behavior?
Show answer
The resource reports resolved, because fetch does not reject on HTTP error statuses, and value() holds the JSON error body. Adding if (!res.ok) throw new Error(HTTP ${res.status}); before the return makes the loader throw, so the resource enters the error status and error() is set.
Exercise
A user sees an error message because a request failed. They then click a link that changes the userId signal read inside params. What happens to the error, and why?
Show answer
The error is cleared. A change to a signal read in params starts a new load, so the resource leaves the error state and goes back to loading. If the new load fails, the resource enters error again with a new error value. If the new load succeeds, it ends in resolved.