Skip to Content
Errors

Send errors across the wire

Send a call's errors from the server to the browser, an RPC client or a worker, and get the same typed errors back.

When your server makes the call and something else shows the result, the failure has to travel too. An Effect RPC, a server-rendered page and a worker only carry data, so each error is encoded to JSON on one side and decoded on the other. Fetch.errorCodec builds the codec that does that: a schema for every error a call can fail with, whose JSON encoding the other side decodes, so it catches the same errors, with the same types, as the server did.

Before you send one, decide whether you should. An HttpError carries the URL your server called and the backend's response text. Often the browser needs less: catch the error on the server, and send an error of your own.

Send a call's errors over an RPC

Give Fetch.errorCodec the endpoint the call uses, and use what it returns as the RPC's error. The following app shares one RPC between the server, which calls the backend, and the browser, which catches the failures:

import * as  from "effect/Effect";
import * as  from "effect/rpc/Rpc";
import * as  from "effect/rpc/RpcClient";
import * as  from "effect/rpc/RpcGroup";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";
import { ,  } from "@monarcode/effetch/plugins";

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

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

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

export class  extends .<>()("Api", {
  : "https://api.example.com",
  : ,
  : { 404:  },
  : [({ : "5 seconds" })],
}) {}

export const  = .("GET /todos/:id", { :  });

// Shared: what the RPC takes, returns and fails with.
export const  = .("GetTodo", {
  : { : . },
  : ,
  : .(, { : , : [] }),
});
export const  = .();

// The server: the call's failures go to the browser as they are.
export const  = .(
  .(function* () {
    const  = yield* ;
    const  = .();
    return { : ({  }) => ({ : {  } }) };
  }),
);

// The browser: the same errors come back, typed as on the server.
export const  = .(function* () {
  const  = yield* .();
  return yield* .({ : 9 }).(
    .(() => .),
    .("TodoNotFound", () =>
      .(`No todo ${.}`),
    ),
    .("HttpError", () =>
      .(.?. ?? `HTTP ${.}`),
    ),
  );
});

In the browser, error.body is an ApiProblem again, decoded from the response text as the server's call decoded it. TodoNotFound comes back as a TodoNotFound. When Api gains another status error, the RPC's errors include it, with nothing else to change.

getTodo here is a definition, made at module level so the browser can import it. A definition only knows its own schemas, so client gives the client's defaultError and statusErrors. An endpoint bound to a client already has both, so inside an Effect, Fetch.errorCodec(todos) is enough.

The browser then imports Api too, and its bundle has the class's config: the baseUrl and the plugins. If those are for the server only, give the schemas themselves instead, as the next section shows, and keep Api in a module the browser doesn't import.

Plugins' errors aren't listed on an endpoint or a client. Add the ones your calls can fail with as errors, such as TimeoutError.

Send the errors of a plain method call

A call made with api.get or the other methods has no endpoint to read. Give Fetch.errorCodec the call's schemas instead:

import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

const  = .({ : . });

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

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

Without output, the errors' type includes a DecodeError, as a call with an output schema can fail with one. An endpoint or a definition that has neither output nor stream can't, so its type leaves it out.

What's sent

Each error goes as JSON, and some of its fields stay on the server:

ErrorWhat's sentWhat stays behind
HttpErrormethod, url, status and textThe headers, which decode as empty, so set-cookie and the like never leave the server. body is decoded again from text.
NetworkErrormethod and urlcause, which decodes as undefined
DecodeErrormethod, url, status and messageissue, which decodes as undefined
Your statusErrors errors, and errorsWhat their own schemas encodeNothing

The URL and the response text do go, and so does a DecodeError's message, which can quote values from the response body. Keep secrets out of the URLs your server calls and out of the backend's responses, or catch the error and send one of your own.

A statusErrors error, or one of errors, whose schema sends no _tag goes with its schema's name: the _tag it leaves out, as Schema.tagDefaultOmit does, or else its identifier, such as a Schema.Class's name. It decodes with the schema that has that name, wherever each side lists it. So when the server and the browser run different versions, an error both know still decodes, and one the browser doesn't know fails to decode, rather than turning into another.

A schema without a name of its own, such as a plain struct or a second class named like another, goes by its place among those, so it only decodes as itself when both sides list them in the same order. The members of a plain Schema.Union each count as a schema. Give errors that cross a _tag, with Schema.TaggedError, or at least an identifier of their own:

import * as  from "effect/Schema";

export const  = .({ : . }).({
  : "ApiProblem",
});

Use the error classes on their own

Fetch.HttpError, Fetch.NetworkError and Fetch.DecodeError are schemas that encode to JSON themselves, so you can also list them in a schema of your own:

import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";

export const  = .([
  .,
  .,
  .,
]);

They send what the table shows, with one difference: they don't know the call's error schema, so an HttpError sends its body when it's JSON, and the other side reads it as unknown. A body decoded into something else, such as a class, stays behind and decodes as undefined. To get a typed body back, use Fetch.errorCodec.

What's next

  • Call errors: see each error a call can fail with, and its fields.
  • Errors by status: turn statuses into errors of your own, which the schema sends too.
  • Endpoints: define the endpoints whose errors you send.

On this page