Catch errors
Handle an error by its tag or its status, and read the API's error body.
When a call fails, you usually want to do something specific: show "You're offline" for a network error, treat a 404 as "nothing there", or show the message the API sent back. Effetch's errors are tagged, so you can pick out each one by name and leave the rest for code further up. This page shows how to catch errors by tag, read the body the API sent with an error, and handle one status at a time. For the errors themselves, see Call errors.
Catch errors by tag
To handle a call's errors, catch them by tag with Effect.catchTags:
import * as from "effect/Effect";
import * as from "effect/Schema";
import type { } from "@monarcode/effetch";
declare const : .;
const = .({ : ., : . });
const = .({ : . });
export const = (: number) =>
.("/todos/:id", { : { }, : , : }).(
.({
: () =>
. === 404
? .()
: .(.?. ?? `HTTP ${.}`),
: () => .("You're offline"),
: () => .(.),
}),
);Each handler gets the error with its fields. You don't have to handle them
all: the ones you leave out stay in the type, for code further up to handle.
To catch a single error, use Effect.catchTag.
For your own helpers, Fetch.FetchError is the union of the three errors,
and Fetch.isFetchError tells them apart from other values.
Read the error body
APIs usually explain an error in its body, such as
{ "code": "not_found" }. Give Effetch a schema for that body, and
HttpError.body is decoded and typed. You can set the schema in two places:
defaultError, on the client, applies to every call.error, on a call or an endpoint, replaces it for that call.
The following client sets defaultError, and one call replaces it with a
schema of its own:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
const = .({ : ., : . });
// Most errors: { "code": "not_found" }
const = .({ : . });
// Errors from POST /todos: { "code": "invalid", "fields": ["title"] }
const = .({
: .,
: .(.),
});
class extends .<>()("Api", {
: "https://api.example.com",
: ,
}) {}
export const = .(function* () {
const = yield* ;
// error.body is { code } | undefined, from defaultError
const = yield*
.("/todos/1", { : })
.(
.("HttpError", () =>
.(`Failed: ${.?. ?? .}`),
),
);
// error.body is { code, fields } | undefined, from error
const = yield*
.("/todos", {
: { : "" },
: ,
: ,
})
.(
.("HttpError", () =>
.(`Check ${.?..(", ") ?? "the form"}`),
),
);
return { , };
});body is typed as your schema or undefined, because the server doesn't
always send what the schema expects:
- With a schema,
bodyis the decoded body, orundefinedwhen it doesn't match. - Without one,
bodyis the parsed JSON, typedunknown, and the call's error type shows a plainHttpError. - With or without one,
bodyisundefinedwhen the response body is empty or isn't JSON.
Reading the body never fails the call: you always get the HttpError. The
raw body is always on text, or "" if it couldn't be read.
For your own function signatures, Fetch.HttpError.With<B> is the type of an
HttpError whose body is B | undefined, as a call with an error schema
shows it.
Catch a status
That covers errors by tag. Often, though, you care about one status rather
than every HttpError. For that, use Fetch.catchStatus, or Fetch.optional
for the common "a 404 means there's nothing there":
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
declare const : .;
const = .({ : ., : . });
// Option<Todo>: none for a 404.
export const = (: number) =>
.("/todos/:id", { : { }, : }).(.);
// "signed out" for a 401 or a 403.
export const =
.("/me")
.(
.([401, 403], () =>
.(`signed out (${.})`),
),
);Fetch.optional succeeds with Option.some(value) when the call succeeds,
and with Option.none() on a 404. Every other error, other statuses
included, passes through.
Fetch.catchStatus takes one status or a list. Keep the following in mind
when you use it:
- The handler gets the
HttpError, withstatusnarrowed to the statuses you gave, and what it returns joins the call's type. HttpErrorstays in the error type, since other statuses still fail with it.- The handler's
error.bodyisunknown. For the body typed by anerrorschema, useEffect.catchTag("HttpError", …)and checkerror.statusyourself. - Both work on endpoint calls too, and on any Effect whose errors include
HttpError.catchStatusalso takes the effect first:Fetch.catchStatus(effect, 404, handler).
A status that statusErrors maps fails with
your error, not an HttpError, so catchStatus and optional don't get it.
Catch your error by its tag instead. That only holds when the body decodes
with your schema, though: a mapped status whose body is empty or doesn't
match still fails with an HttpError, which catchStatus does catch.
What's next
- Errors by status: fail with your own error for a status, and catch it by its tag.
- Client configuration: set
defaultErrorwith the client's other options. - Test errors and statuses: check your handlers against a fake backend.