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 the status signals from the earlier chapters. It covers what happens when a loader fails and how to show that to the user.
What counts as a failure
A resource enters the error status when its loader throws, or when its Promise rejects. The error() signal then holds the thrown value, and value() no longer holds data.
The fetch function does not reject on HTTP 4xx or 5xx responses. It only rejects on network failures. If you skip the res.ok check, a 404 response body is parsed as data and the resource shows resolved. Throw an error yourself:
import { Component, resource, signal } from '@angular/core';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-errors',
template: `
@if (user.error(); as err) {
<p>Could not load the user.</p>
<button (click)="user.reload()">Try again</button>
} @else if (user.isLoading()) {
<p>Loading...</p>
} @else if (user.hasValue()) {
<p>{{ user.value().name }}</p>
}
`,
})
export class UserErrorsComponent {
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 Error(`HTTP ${res.status}`);
return (await res.json()) as User;
},
});
}Checking the error before the value
The order of the template branches matters. Check error() first, then isLoading(), then the value. In recent Angular versions, reading value() while the resource is in the error state throws. Older releases returned undefined instead. Guarding with hasValue() works in both cases, because it returns false when there is no usable value.
error() is typed as unknown or Error, depending on the version. Do not assume it has a particular shape. To show a message, narrow it first:
import { Component, resource } from '@angular/core';
@Component({
selector: 'app-message',
template: `<p>{{ message() }}</p>`,
})
export class MessageComponent {
readonly data = resource({
loader: async () => {
throw new Error('HTTP 500');
},
});
message(): string {
const err = this.data.error();
return err instanceof Error ? err.message : 'Something went wrong.';
}
}How a resource recovers
A resource does not retry on its own. It leaves the error state in one of two ways:
- A signal read in
paramschanges. The loader runs again with the new input, and the status goes toloading. - You call
reload(). The loader runs with the same params.
If a request is cancelled because params changed, the cancelled loader's failure is ignored. Only the newest request decides the final status. This is why you should pass abortSignal to fetch. An AbortError from a superseded request never reaches your template.
Choosing where to handle errors
You have two places to deal with a failure:
| Place | Use it for |
|---|---|
| Inside the loader (try/catch) | Turning a known failure into a fallback value, such as a 404 becoming `null` |
| In the template, via `error()` | Showing a message and a retry button for unexpected failures |
Catching inside the loader hides the failure from the status signals. Do that only when the failure is expected and the resource should still end up resolved. Let unexpected errors reach error().
Exercise
A loader calls fetch('/api/orders') and the server answers 500, but the resource status is resolved and the template shows garbage. What is missing, and what should the loader do?
Show answer
The loader never checks res.ok. fetch only rejects on network errors, so a 500 response is parsed as data. Add if (!res.ok) throw new Error(HTTP ${res.status}); before parsing the body. The resource then enters the error state and error() holds the thrown error.