Typed errors become status codes

By Esteban Trillo6 min readupdated Effect on the BackendEffectTypeScript

One error class, one status: UserNotFound carries its 404 from the endpoint to the client, which catches it by name.
One error class, one status: UserNotFound carries its 404 from the endpoint to the client, which catches it by name.

Part 6 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the part-6 tag.

GET /users/2 has answered 500 since part 3. Nobody has user 2, so it should be a 404, and part 5 made it worse: to get past tsc I wrapped getUser in Effect.orDie, which turns a missing user into a defect. And every 400 lost its body when the routes moved into the contract, so a client sending a bad email got an empty response and had to guess.

Learning Effect part 11 did the 404 by hand: catchTag("UserNotFound") and build a Response with status 404. That works for one route. This part puts the status on the error class instead, declares the error on the endpoint, and lets HttpApi write the response.

The error carries its status

UserNotFound has been a Data.TaggedError since part 1. HttpApi has to encode the error into a response body, and the client has to decode it back, so it needs a schema. Schema.TaggedError is the same idea with a schema attached, and its third argument takes annotations:1

src/Users.ts (excerpt)
export class UserNotFound extends Schema.TaggedError<UserNotFound>()(
"UserNotFound",
{ id: Schema.String },
{ httpApiStatus: 404 },
) {
override get message() {
return `user ${this.id} not found`
}
}

The rest of Users.ts doesn’t change. find still does yield* new UserNotFound({ id }), and part 2’s Effect.fn spans and traces still work, because a Schema.TaggedError is still a yieldable error.

The endpoint declares it with error:, next to success::

src/Api.ts (excerpt)
HttpApiEndpoint.get("get", "/users/:id", {
params: UserParams,
success: User,
error: UserNotFound,
}),

And the handler loses its orDie:

src/main.ts (excerpt)
.handle("get", ({ params }) => getUser(params.id))

That’s the whole 404. The handler’s error type is now UserNotFound, which the contract allows, so tsc is happy. At runtime HttpApi catches the failure, finds the matching schema in the endpoint’s error list, encodes the error with it, and answers with that schema’s status:

curl localhost:3000/users/2
404 {"_tag":"UserNotFound","id":"2"}

The body is the error’s fields and its tag. The message getter isn’t a field, so it isn’t sent.

The 400 gets its body back

A request that fails to decode never reaches the handler, so it has no error type to declare. HttpApi answers it with an empty 400. To change that, HttpApiMiddleware.layerSchemaErrorTransform catches the decode failure and lets you fail with an error of your own.2 The error goes in the contract, so the client and the OpenAPI document know about it:

src/Api.ts (excerpt)
export class BadRequest extends Schema.TaggedError<BadRequest>()(
"BadRequest",
{
issues: Schema.Array(Schema.Struct({ message: Schema.String, path: Schema.Array(Schema.String) })),
},
{ httpApiStatus: 400 },
) {}
export class Validation extends HttpApiMiddleware.Service<Validation>()("Validation", {
error: BadRequest,
}) {}
export const Api = HttpApi.make("api")
.add(UsersGroup)
.middleware(Validation)
.annotate(HttpApi.PayloadParseOptions, { errors: "all" })

.middleware(Validation) on the HttpApi adds it to every endpoint already in it. The annotation brings back what part 5 lost: part 4 decoded bodies with errors: "all", and HttpApi stops at the first bad field unless you tell it otherwise.

The implementation lives in main.ts, because the client imports Api.ts and doesn’t need it. It’s part 4’s formatter, moved from two catchTags into one place:

src/main.ts (excerpt)
const format = SchemaIssue.makeFormatterStandardSchemaV1()
const ValidationLive = HttpApiMiddleware.layerSchemaErrorTransform(Validation, (error) => {
const issues = format(error.cause.issue).issues.map((issue) => ({
message: issue.message,
path: (issue.path ?? []).map(String),
}))
return Effect.fail(new BadRequest({ issues }))
})
const ApiRoutes = HttpApiBuilder.layer(Api, { openapiPath: "/openapi.json" }).pipe(
Layer.provide(UsersLive),
Layer.provide(ValidationLive),
)

main.ts went from 22 non-blank lines to 31, and those nine lines replace the invalid and notJson helpers that every part 4 route called. Here’s every request part 5 got wrong, before and after:

Pick a request
Part 5
500, empty body. The log prints UserNotFound: user 2 not found with a stack trace, at INFO.
Part 6
404 {"_tag":"UserNotFound","id":"2"}. The log says Sent HTTP response, status 404.
Typed client
Fails with a UserNotFound you can catchTag. Its message is "user 2 not found", rebuilt from the id.
Part 5
Empty 400. The log has the reason: Expected a positive integer at ["id"].
Part 6
400 {"_tag":"BadRequest","issues":[{"message":"Expected a positive integer","path":["id"]}]}
Typed client
Can't send it. UserId.make("abc") throws before any request.
Part 5
Empty 400. The log names the name and stops there.
Part 6
400 with two issues: a length of at least 1 at name, and Expected an email address at email.
Typed client
Fails with a SchemaError before sending. The server never sees it.
Part 5
Empty 400. The log says Expected a valid JSON body.
Part 6
400 {"_tag":"BadRequest","issues":[{"message":"Expected a valid JSON body","path":[]}]}
Typed client
Can't send it. The client always sends JSON it encoded itself.
Part 5
415 Unsupported content-type, as plain text.
Part 6
The same 415. It's answered before decoding starts, so the middleware never sees it.
Typed client
Can't send it. The client sets the content type.

The 415 is the one that didn’t move. HttpApi refuses the content type before it decodes anything, so there’s no schema error to transform. POST /users/1 and /nope are still empty 404s too: no route matched, so no endpoint, so no contract.

You move .middleware(Validation) before .add(UsersGroup) in Api.ts. What does GET /users/abc answer?

The client catches it by name

The client reads the same contract, so get now fails with a UserNotFound you can catch:

src/client.ts (excerpt)
const missing = yield* client.users
.get({ params: { id: UserId.make("999") } })
.pipe(Effect.catchTag("UserNotFound", (error) => Effect.succeed(error.message)))
node src/client.ts (trimmed)
{
created: { id: '3', name: 'Grace', email: 'grace@example.com' },
found: { id: '3', name: 'Grace', email: 'grace@example.com' },
missing: 'user 999 not found'
}

The body only had _tag and id, but missing is the getter’s text. The client decoded the body into the UserNotFound class itself, so the getter came along on the client’s side. It isn’t a lookalike object. It’s an instance of the same UserNotFound class the server failed with.

What the types tell you

src/part-6/types.ts is type-check only. Here’s npm run check without its @ts-expect-error lines:

npm run check (without the expect-error lines, trimmed)
error TS2375: Type 'Effect<{ … }, UserNotFound, Users>' is not assignable to type 'Effect<{ … } | HttpServerResponse, BadRequest, Users>'
Property 'issues' is missing in type 'UserNotFound' but required in type 'BadRequest'.
error TS2769: No overload matches this call.
Type 'typeof Gone' is not assignable to type 'Top | readonly Top[] | undefined'.
error TS2345: Argument of type '"UserNotFound"' is not assignable to parameter of type '"BadRequest" | "HttpClientError" | "SchemaError" | …'.

The first is part 5’s last error, moved to create, which doesn’t declare UserNotFound. The allowed error type isn’t never anymore, though. It’s BadRequest, because a handler can fail with any error its middleware declares. The second is a Data.TaggedError passed to error:. It has no schema, so HttpApi couldn’t encode it. The third is the client: create can fail with a BadRequest, a network error or a client-side SchemaError, and catchTag("UserNotFound") on it doesn’t compile, because create can’t return one.

The OpenAPI document reads the same declarations. GET /users/{id} now lists 200, 400 and 404, and POST /users lists 201 and 400. Part 5’s spec had no 400 anywhere.

The gotchas, and when not to bother

src/part-6/gotchas.ts builds a small API with HttpRouter.toWebHandler and calls it without a server:

node src/part-6/gotchas.ts
middleware after: GET /locked 500 {"_tag":"Locked","reason":"row 42 held by job 7 (pg pid 3141)"}
middleware after: GET /items/abc 400 {"_tag":"BadRequest","issues":[…]}
middleware before: GET /locked 500 {"_tag":"Locked","reason":"row 42 held by job 7 (pg pid 3141)"}
middleware before: GET /items/abc 400
  • An error with no status is a 500 with its fields in the body. Locked is declared on the endpoint but has no httpApiStatus. The default is 500, encoded as JSON like any other declared error, so reason goes to the caller. The server log for it is one line, Sent HTTP response with status 500, and no error. The caller sees the internal detail, and your log doesn’t.
  • Middleware order matters, and nothing checks it. That’s the quiz: .middleware() only covers endpoints added before it.
  • The log lost the reason. Part 5 logged HttpApiSchemaError: Params with the issue under it. Now the reason is in the response, and the log line says Sent HTTP response and the status. For a 404 and a 400 that’s what I want. If you need to see why clients get 400s, log in the transform.
  • Not every 4xx goes through it. The 415 and the unmatched routes above are answered outside the contract, with no body you control.

The bigger question is whether Users.ts should know about HTTP at all. httpApiStatus: 404 is only an annotation and the file imports nothing from effect/http, but it’s still a status code on a domain error. I’m fine with it here. This service has one caller, it’s the HTTP API, and a missing user is a 404 everywhere it shows up. When the same service also serves a queue consumer or the RPC from part 16, I’d keep the domain error plain and map it at the HTTP edge, in the handler, to HttpApiError.NotFound, one of the built-in errors with its status already set.

When not to bother: an error the caller can’t act on. A failed database connection isn’t something to declare on an endpoint. Let it be a defect, an empty 500, and log it on the server.

Run it

Terminal window
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-6
npm install
npm start

Then curl -i localhost:3000/users/2 for the 404, and node src/client.ts in another terminal. src/part-6/ has the gotchas script and the type errors.

The port is still 3000, hard-coded since part 3.

Next in the series: config and secrets, where the port comes from the environment.

  • Part 7 — Config and secrets: The port and the database URL come from the environment, a bad value stops the server before it listens, and the password logs as <redacted>.

Footnotes

  1. HTTPAPI.md at the effect@4.0.5 tag, “Adding Custom Error Responses” and “Predefined Error Types”. The guide shows HttpApiSchema.status(404) on a plain schema and { httpApiStatus: 401 } on a Schema.TaggedError. Both set the same annotation. ↩

  2. HTTPAPI.md, “Customizing Schema Error Responses”. The guide’s example answers 422; this repo keeps part 4’s 400. The empty 400 comes from HttpApiSchemaError in effect/src/http-api/HttpApiError.ts. ↩

Read next

  1. Config and secretsNov 14, 2026 Effect on the Backend · 5 min
  2. HttpApi: define the API onceNov 12, 2026 Effect on the Backend · 7 min
  3. Wiring a real app with layersNov 15, 2026 Effect on the Backend · 6 min
  4. Schema at the boundaryNov 11, 2026 Effect on the Backend · 6 min
  5. SQL and migrations with effect/sqlNov 16, 2026 Effect on the Backend · 6 min
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.