Queries
Errors by status
Turn an HTTP status into a typed domain error.
Effetch's statusErrors turns error responses into your own errors: a
status maps to the schema of the error it means, or to a list 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:
The examples import api.ts and todos.ts from Getting started.
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
: .,
}) {}
const = .(
.("GET /todos/:id", {
: ,
: { 404: , 403: [] },
}),
);
// 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.</>)
.(() => <>{.}</>)
.();
}- A response no schema decodes (another 403, a body that isn't JSON)
fails with the
HttpErrorit would without them, soHttpErrorstays in the error type. - The client's
statusErrors(declared with the client, as inFetch.Service<ApiClient>()("ApiClient", { statusErrors })) apply to every endpoint, and are typed from the client's service.fromClientreads them from theFetch.Serviceclass, so server rendering sends them too. For a client behind aContext.Servicekey, give them tofromClient(A client that isn't aFetch.Serviceclass). - Server rendering sends them as themselves with
failures: "include": aTodoNotFoundon the server is aTodoNotFoundin the browser, with no refetch. - Their schemas, like
output's, can only need your registered services.RegisteredStatusErrorsis the type of such a map, to check one you define on its own withsatisfies RegisteredStatusErrors.
A detail that may not exist. To show a missing todo as no todo rather
than a failure, write the query yourself with Fetch.optional, which
turns a 404 into Option.none():
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) =>
.(() =>
.(.()({ : { } })),
),
// For server rendering: an Option of a todo.
: { : .(), : . },
});
// maybeTodo(1): Query<Option<Todo>, …>