Error handling
HyperFetch requests do not reject by default. send() resolves with error and status next to data for every
failure: an HTTP error, a timeout, an abort or a dropped connection. This guide shows the kinds of errors you get, how to
type them, where to handle them and how to reject when your code needs it.
- How to read errors without
try/catch. - Which kinds of errors a request returns.
- How to type a global error on the client and a local error per request.
- How to narrow the error union and handle errors in one place.
- How to reject on errors with
throwOnError.
Read the error from the response
Branch on data or error instead of catching. status tells an HTTP error from a failure that never reached the
server.
const { data, error, status } = await getUser.send({ params: { userId: 1 } });
if (data) {
renderUser(data);
} else {
showError(status, error);
}
Prefer checking data over success. success does not narrow the types, so data stays nullable after
if (success).
Kinds of errors
| Cause | error | status |
|---|---|---|
| The server answered 4xx or 5xx | The parsed response body | The HTTP status |
| No connection, DNS or CORS failure | The fetch error, usually TypeError | 0 |
| Timeout (fetch adapter, default 5000 ms) | TimeoutError | 0 |
Aborted with abort(), cancelable or a signal | AbortError | 0 |
| Removed from the queue before it ended | DeletedError | null |
| A mapper or interceptor threw | The thrown value | The response status |
The first row is your API's error shape. The others are Error instances, exported from @hyper-fetch/core, so you can
check them with instanceof.
Type the global error
Type your API's error body once on the client with the error generic. Keep Error in the union, because the system
failures above are Error instances.
import { createClient } from "@hyper-fetch/core";
export type ApiError = { message: string; code: string };
export const client = createClient<{ error: ApiError | Error }>({
url: "https://api.example.com",
});
Every request of this client now has error typed as ApiError | Error | null. See
global error.
Add a local error per request
Some endpoints return their own error shape, such as field errors of a form. Add it with the request's error generic.
It is joined with the global error into a union.
type ValidationError = { fields: Record<string, string[]> };
export const signUp = client.createRequest<{
response: User;
payload: { email: string; password: string };
error: ValidationError;
}>()({ endpoint: "/users", method: "POST" });
// error: ValidationError | ApiError | Error | null
See local error.
Narrow the error
Check system errors with instanceof, then tell API shapes apart by a property only one of them has.
import { AbortError, TimeoutError } from "@hyper-fetch/core";
const { data, error } = await signUp.send({ payload: { email, password } });
if (error instanceof AbortError) {
// The user canceled, nothing to show
} else if (error instanceof TimeoutError) {
showToast("The server took too long. Try again.");
} else if (error instanceof Error) {
showToast("Check your connection.");
} else if (error && "fields" in error) {
showFieldErrors(error.fields);
} else if (error) {
showToast(error.message);
}
Handle errors in one place
client.onError runs for every failed response, before send() resolves. Use it for logging, a global toast or
refreshing a token. Return the response, changed or not.
client.onError((response, request) => {
if (response.status && response.status >= 500) {
reportToMonitoring({
endpoint: request.endpoint,
status: response.status,
error: response.error,
});
}
return response;
});
To turn errors of another shape into yours, map them in setResponseMapper, see
data mapping. To retry failed requests, see
retries.
Reject on errors with throwOnError
Some code tells failures by a rejected promise: query functions of TanStack Query, fetchers of SWR, route loaders and
Promise.all. Set throwOnError and send() or exec() rejects with the error of a failed response. A successful
response resolves as usual. Default false: change it per call, per request or for many requests at once.
// Per call
const { data } = await getUser.send({ throwOnError: true });
// Per request
const getUser = client
.createRequest<{ response: User }>()({ endpoint: "/users/:id" })
.setThrowOnError(true);
// For many requests. This replaces the adapter's defaults,
// so keep deduplication of reads, which the fetch adapter sets.
client.adapter.setRequestDefaults((options) => ({
deduplicate: (options.method ?? "GET") === "GET",
throwOnError: options.endpoint.startsWith("/admin"),
}));
The call wins over the request, and the request wins over the defaults. TypeScript does not type rejections, so narrow
the caught value like error above. The React hooks ignore the option and keep errors in their state. To throw into
an error boundary, use the throwOnError option of useFetch.
You've learned how to handle errors.
- You can read errors from the response without
try/catch. - You can tell API errors from system errors such as
TimeoutErrorandAbortError. - You can type a global error on the client and a local error per request.
- You can handle errors in one place with
client.onError. - You can make
send()andexec()reject withthrowOnError.
Runnable examples: Error handling and Typed errors.