Query errors
What a failed query holds, how to turn a status into your own error, how to handle each one, and how to retry.
A request fails: the server answers a missing todo with a 404, the network drops, or a response doesn't match its schema. Effetch Query keeps the error typed from the query to the component, so you can show "This todo was deleted" for one and "Couldn't load it" for the rest. This page shows what a failure holds, how to turn a status into an error of your own, how to handle each error, and how to retry.
The examples import api.ts and todos.ts from
Getting started.
What a failure holds
A query's error type is part of its type: Query<A, E>. A failed query's
result is a Failure with the full Cause, Effect's record of why an
Effect ended. The Cause tells three things apart:
- the query's errors, typed as
E; - defects, unexpected throws, such as a bug;
- interruptions, when the query's own Effect is interrupted. A fetch that a refetch replaces isn't one, and never shows as a failure.
A query from any Effect fails with whatever its Effect fails with. An
endpoint query's E is a union of these:
| Error | When it happens |
|---|---|
NetworkError | The request never got a response: the device is offline, or the connection was refused. |
HttpError | The server answered with a status other than 2xx, and no error by status matched it. |
DecodeError | The response didn't match the endpoint's output. Only an endpoint with an output has it. |
| Your plugins' errors | An Effetch plugin the client uses failed the call. |
| Your errors by status | A status mapped to an error of your own, as Errors by status shows. |
The body of an HttpError is typed by the client. ApiClient in
api.ts declares defaultError: ApiError, so every endpoint's
HttpError is HttpError.With<{ message: string }>. An endpoint with an
error schema of its own uses that one instead. todo.error holds
whichever schema applies, and ErrorSchema is that choice as a type.
Errors by status
An HttpError with a 404 status says less than a TodoNotFound. Effetch's
statusErrors maps a status to the schema of the error it means, or to a
list of schemas tried in order, where a literal field picks one. Queries
and mutations made from such an endpoint fail with those errors, typed, so you handle
them by their tag.
Here is todo from todos.ts with a map on its endpoint. In your app, it
replaces the todo that todos.ts defines:
import * as from "effect/Effect";
import * as from "effect/reactivity/AsyncResult";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query";
import { } from "@monarcode/effetch-query/react";
import { } from "./api.js";
import { } from "./todos.js";
class extends .<>()("TodoNotFound", {
: .,
}) {}
class extends .<>()("NotYourTodo", {
: .("NOT_OWNER"), // only a 403 with this code
: .,
}) {}
// `todo` from todos.ts, with its errors by status on the endpoint.
const = .(
.("GET /todos/:id", {
: ,
: { 404: , 403: [] },
}),
{ : "1 minute" },
);
// In a loader: a missing todo is no todo.
export const = (: number) =>
.(({ : { } })).(
.("TodoNotFound", () => .()),
);
export function ({ }: { readonly : number }) {
return .((({ : { } })))
.(() => <>Loading…</>)
.("TodoNotFound", () => <>This todo was deleted.</>)
.("NotYourTodo", () => <>{.}</>)
.(() => <>Couldn't load it.</>)
.(() => <>{.}</>)
.();
}todo fails with TodoNotFound on a 404, and with NotYourTodo on a 403
whose body has the code NOT_OWNER. A few rules decide the rest:
- A response no schema decodes falls through. Another 403, or a body
that isn't JSON, fails with the
HttpErrorit would without a map, soHttpErrorstays in the error type. - The client can have a map too. Declared with the client, as in
Fetch.Service<ApiClient>()("ApiClient", { statusErrors }), it applies to every endpoint, typed from the client's service. For a given status, the endpoint's schemas are tried before the client's. fromClientreads the client's map from itsFetch.Serviceclass, so server rendering sends those errors too. For a client behind aContext.Servicekey, give the map tofromClient, as A client that isn't aFetch.Serviceclass shows.- A status error's schema, like
output, can use only your registered services.RegisteredStatusErrorsis the type of such a map: check one you define on its own withsatisfies RegisteredStatusErrors. - Server rendering sends them as themselves with
failures: "include": aTodoNotFoundon the server is aTodoNotFoundin the browser. The first component that reads it retries it, as the mount policy says, unlessretryOnMountisfalse.
Handle an error
In Effect code, Query.fetch fails with the query's error, so
Effect.catchTag handles one error by its tag and lets the others
through. In the sample, loadTodo turns a TodoNotFound into no todo,
which suits a route loader. Read and write the cache shows
Query.fetch and the other cache functions.
In a component, AsyncResult.builder matches the typed errors by their
_tag: onErrorTag for each error you handle, then onError for the
rest, as TodoTitle does. To match by kind instead (typed error, defect),
use AsyncResult.matchWithError. Read a query shows both.
Show a missing record as no value
Sometimes a missing todo isn't an error: a page shows "No todo" and moves
on. Write the query yourself with Effetch's Fetch.optional, which turns
a 404 into Option.none() and a success into Option.some:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query";
import { , } from "./api.js";
import { } from "./todos.js";
export const = .({
: ["todos", "maybe"],
: (: number) =>
.(() =>
.(.()({ : { } })),
),
// How the value crosses to the browser: an Option of a todo.
: { : .() },
});
// maybeTodo(1): Query<Option<Todo>, …>Other errors still fail the query. A 404 that statusErrors maps fails
with the mapped error, and doesn't give Option.none(): use an endpoint
without a 404 in its map, as getTodo is.
Retry a failed fetch
A query doesn't retry by default, where TanStack Query retries three
times. Effetch has a retry plugin, and a query shouldn't retry what the
client already retried. To retry at the query, give it a retry
schedule:
import * as from "effect/Schedule";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "./todos.js";
export const = .(
.("GET /stats", {
: .({ : ., : . }),
}),
// Two more tries before the failure shows.
{ : .(2) },
);The schedule gets each failure, and defects aren't retried. The client's
queries.defaults.retry sets a schedule for every query, and the client's
onFailure hook runs once per fetch, after retry. See
Defaults and app-wide hooks.
What's next
- Read a query: show each state of a query, errors included, in a component.
- Suspense and error boundaries: let an error boundary show a failure.
- Defaults and app-wide hooks: retry every query, and report every failure from one place.
- Send the cache: send failures from the server
with
failures: "include".