Skip to Content
Effetch Query
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 HttpError it would without them, so HttpError stays in the error type.
  • The client's statusErrors (declared with the client, as in Fetch.Service<ApiClient>()("ApiClient", { statusErrors })) apply to every endpoint, and are typed from the client's service. fromClient reads them from the Fetch.Service class, so server rendering sends them too. For a client behind a Context.Service key, give them to fromClient (A client that isn't a Fetch.Service class).
  • Server rendering sends them as themselves with failures: "include": a TodoNotFound on the server is a TodoNotFound in the browser, with no refetch.
  • Their schemas, like output's, can only need your registered services. RegisteredStatusErrors is the type of such a map, to check one you define on its own with satisfies 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>, …>