Errors by status
Turn an error status into your own domain error.
Often a status, or a status with a given body, means a specific error in
your app: a 404 from GET /todos/:id is "todo not found", a 400 with
"code": "INVALID_ROLE" is "invalid role", a 401 from anywhere is "session
expired". statusErrors maps statuses to your own error schemas, and the
call fails with your error instead of an HttpError. This page shows how to
set up those maps and how Effetch picks the error for a response.
Choose where a map applies
You can give a map in three places, and they add up:
- on the client, for every call, such as a
401from anywhere; - on an endpoint, for every call to it, which is where most of them live;
- on a single call.
Map statuses to your errors
The following program gives a map in all three places, 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: a response can always fail to match.
How a response is resolved
Effetch resolves a non-2xx response in the following order:
- If the body is empty or isn't JSON, it's an
HttpError. - Otherwise the schemas listed for its status are tried in order: the call's, then the endpoint's, then the client's. The first one that decodes the body is the error.
- If none does, it's the
HttpErroryou'd get withoutstatusErrors, itsbodydecoded witherrorordefaultError.
With the maps from the program in Map statuses to your errors, responses fail as follows:
| Response | Fails 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 body | HttpError |
| 401 from any endpoint | SessionExpired |
| 500 | HttpError |
- The
_tag. Backends don't send one, so when a schema has a literal_tag, asSchema.TaggedErrorclasses do, Effetch adds it to the body before decoding. A body that has its own_tagis decoded as it is. - Renamed fields. To read
error_codeintocode, useSchema.encodeKeys:InvalidRole.pipe(Schema.encodeKeys({ code: "error_code" })). - Lists, not unions. A
Schema.Unionis decoded as it is, without a_tag: list its members instead. - 2xx entries never apply, since a 2xx is decoded with
output. - Plugins see the response before any of this, so
retrystill retries by status.onErrorreceives your error, andapi.httpClientstays raw. - Maps are copied when they're given, so changing one afterwards changes
nothing.
api.statusErrorsand aFetch.endpointdefinition'sstatusErrorsare those copies, frozen; an endpoint'sstatusErrorsjoins its own with the client's, each status listing its schemas in the order they're tried. Fetch.StatusError<M>is the union of the errors in a mapM, andFetch.StatusErrorSchema<M>the union of its schemas, for your own function signatures.- A client's type includes its map:
Fetch.Client<Ps, EB, SE>. A client with a map can't be passed where a plainFetch.Clientis expected, since that would hide its errors.
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
- Catch errors: catch your errors, and the statuses you didn't map.
- Define endpoints: put each endpoint's
statusErrorson its definition. - Test errors and statuses: make a fake backend answer with an error status.