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.getorapi.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:
- 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 or 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, with itsbodydecoded byerrorordefaultError.
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 { "message": "…" } from any endpoint | SessionExpired |
| 401 with an empty body | HttpError |
| 500 | HttpError |
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.
- 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, so list its members instead. - 2xx entries never apply, since a 2xx is decoded with
output. - Plugins get the response first. They run 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 made withapi.endpointorapi.bindhasstatusErrorsthat join its own with the client's, each status listing its schemas in the order they're tried. - Types.
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.
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
- 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.