Skip to Content
Errors

Errors by status

Turn an error status into your own domain error.

An error status often means something specific in your app. A 404 from GET /todos/:id means "todo not found", a 400 with "code": "INVALID_ROLE" means "invalid role", and a 401 with a message from any endpoint means "session expired". Catching each of these as an HttpError and checking its status at every call gets repetitive. statusErrors maps statuses to error schemas of your own, so the call fails with your error instead of an HttpError, and the error's tag says what went wrong. This page shows how to set up those maps, and how Effetch picks the error for a response.

Map statuses to your errors

A map's keys are statuses, and each value is an error schema, or a list of them to try in order. The following program gives a map on the client, on an endpoint and on one call, then catches the errors by their tags:

import * as  from "effect/Effect";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

class  extends .<>()("TodoNotFound", {
  : .,
}) {}

class  extends .<>()("InvalidRole", {
  : .("INVALID_ROLE"),
  : .,
}) {}

class  extends .<>()("RoleTaken", {
  : .("ROLE_TAKEN"),
  : .,
}) {}

class  extends .<>()(
  "SessionExpired",
  { : . },
) {}

const  = .({ : . });
const  = .({ : ., : . });
const  = .({ : ., : . });

// For every call
export class  extends .<>()("Api", {
  : "https://api.example.com",
  : ,
  : { 401:  },
}) {}

// For every call to an endpoint (see Endpoints)
export const  = .("GET /todos/:id", {
  : ,
  : { 404:  },
});

export const  = .(function* () {
  const  = yield* ;
  const  = yield* 
    .()({ : { : 1 } })
    .(.("TodoNotFound", () => .()));

  // For one call
  const  = yield* 
    .("/users/:id/roles", {
      : { : 1 },
      : .({ : . }),
      : { : "owner" },
      : ,
      : { 400: [, ] }, // tried in order
    })
    .(
      .({
        : () => .(.),
        : () => .(.),
      }),
    );
  return { ,  };
});

Before the catchTags, the role call fails with InvalidRole | RoleTaken | SessionExpired | HttpError.With<{ readonly code: string }> | NetworkError | DecodeError. HttpError stays in the type, because a response can always fail to match your schemas.

Choose where a map applies

As the program shows, you can give a map in three places, and they add up:

  • On the client, for every call, such as a 401 from anywhere.
  • On an endpoint, for every call to it. Most maps live here, next to the route they describe.
  • On a single client call, such as api.get or api.post.

An endpoint call takes no map of its own. It uses the endpoint's map and the client's, so to add a status for one endpoint, put it on the endpoint's definition.

How a response is resolved

When a response comes back with a non-2xx status, Effetch picks the error in the following order:

  1. If the body is empty or isn't JSON, it's an HttpError.
  2. Otherwise, the schemas listed for its status are tried in order: the call's or the endpoint's, then the client's. The first one that decodes the body is the error.
  3. If none does, it's the HttpError you'd get without statusErrors, with its body decoded by error or defaultError.

With the maps from the program in Map statuses to your errors, responses fail as follows:

ResponseFails with
400 { "code": "INVALID_ROLE", "message": "…" }InvalidRole
400 { "code": "ROLE_TAKEN", "message": "…" }RoleTaken
400 { "code": "MISSING_FIELD" }HttpError with body.code
400 with an empty or non-JSON bodyHttpError
401 { "message": "…" } from any endpointSessionExpired
401 with an empty bodyHttpError
500HttpError

The empty 401 is the case to watch for. Some servers send a 401 or a 404 with no body at all, and statusErrors can't map a body that isn't there. For a status whose body may be empty, catch the HttpError with Fetch.catchStatus, alongside your error's tag.

Test a map

To check that a status turns into your error, make a fake backend answer with it. FetchTest.fail(getTodo, 401, new SessionExpired({ message: "…" })) sends the error as JSON, and the client decodes it back into SessionExpired. When the endpoint has no error or statusErrors schema of its own, this works with a map that's only on the client, so you don't need to repeat it on the endpoint. See Test errors and statuses.

See it in a full program

examples/status-errors.ts puts all of this in one program, and examples/app uses it across modules.

What's next

On this page