Skip to Content
Errors

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, body is the decoded body, or undefined when it doesn't match.
  • Without one, body is the parsed JSON, typed unknown, and the call's error type shows a plain HttpError.
  • With or without one, body is undefined when 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, 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.
  • The handler's error.body is unknown. For the body typed by an error schema, use Effect.catchTag("HttpError", …) and check error.status yourself.
  • Both work on endpoint calls too, and on any Effect whose errors include HttpError. 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 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

On this page