Skip to Content
Errors

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, with status narrowed to the statuses you gave, and what it returns joins the call's type.
  • HttpError stays in the error type, since other statuses still fail with it.
  • Both work on endpoint calls too, and catchStatus also 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 never see it. Catch your error by its tag instead.
  • The handler's error.body is unknown. For the typed body of an error schema, use Effect.catchTag("HttpError", …).

What's next

On this page