Catch errors
Handle an error by its tag, or one status.
This page shows how to handle a call's errors: by their tag, or by the response's status. 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.
For a single error, Effect.catchTag does the same.
Fetch.FetchError is the union of the three errors, and Fetch.isFetchError
tells them apart from other values.
Catch a status
To handle one or more statuses, use Fetch.catchStatus. For the common "a
404 means there's nothing there", Fetch.optional succeeds with
Option.none() on a 404 and Option.some(value) otherwise.
The following example uses both:
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 (${.})`),
),
);Keep the following in mind when you catch a status:
- 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.- Both work on endpoint calls too, and
catchStatusalso takes the effect first:Fetch.catchStatus(effect, 404, handler). - A status that
statusErrorsmaps fails with your error, not anHttpError, socatchStatusandoptionalnever see it. Catch your error by its tag instead. - The handler's
error.bodyisunknown. For the typed body of anerrorschema, useEffect.catchTag("HttpError", …).
What's next
- Typed error bodies: type
error.bodywith a schema. - Errors by status: fail with your own error for a status, and catch it by its tag.
- Test errors and statuses: check your handlers against a fake backend.