Skip to main content
Version: v10.5.0

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.

What you'll learn
  1. How to read errors without try/catch.
  2. Which kinds of errors a request returns.
  3. How to type a global error on the client and a local error per request.
  4. How to narrow the error union and handle errors in one place.
  5. 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.

src/app.ts
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​

Causeerrorstatus
The server answered 4xx or 5xxThe parsed response bodyThe HTTP status
No connection, DNS or CORS failureThe fetch error, usually TypeError0
Timeout (fetch adapter, default 5000 ms)TimeoutError0
Aborted with abort(), cancelable or a signalAbortError0
Removed from the queue before it endedDeletedErrornull
A mapper or interceptor threwThe thrown valueThe 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.

src/api/client.ts
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.

src/api/users.ts
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.

src/sign-up.ts
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.

src/api/client.ts
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.

src/api/client.ts
// 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.


Congratulations!

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 TimeoutError and AbortError.
  • 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() and exec() reject with throwOnError.

Runnable examples: Error handling and Typed errors.

Global error type
Type the error shape of your API once.
Retries
Retry failed requests with backoff.
Request
What send() resolves with.