# Typed errors become status codes

- Published: 2026-11-13
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-6-typed-errors-become-status-codes/

> Part 6 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-6), and this part is the `part-6` tag.

`GET /users/2` has answered 500 since [part 3](/writing/effect-backend-3-a-node-server-in-20-lines/). Nobody has user 2, so it should be a 404, and [part 5](/writing/effect-backend-5-httpapi-define-once/) 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](/writing/learning-effect-11-one-small-real-program/) 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](/writing/effect-backend-1-what-changed-in-effect-4/). 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:[^errors]

```ts title="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:`:

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

And the handler loses its `orDie`:

```ts title="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:

```text title="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.[^transform] The error goes in the contract, so the client and the OpenAPI document know about it:

```ts title="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](/writing/effect-backend-4-schema-at-the-boundary/) 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 `catchTag`s into one place:

```ts title="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:

**One request, and what the server answered in part 5 and in part 6.**

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

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

- The same 400 with a BadRequest body
- An empty 400
- A tsc error, because ValidationLive is provided but unused

**Answer:** An empty 400 — The group is added after the middleware, so its endpoints don't have it. tsc says nothing, and the request gets the default empty 400. src/part-6/gotchas.ts runs both orders.

- Not "The same 400 with a BadRequest body": That's what you'd get if middleware covered the whole API. It only reaches endpoints that are already in it.
- Not "A tsc error, because ValidationLive is provided but unused": Providing a layer nothing uses is allowed.

## The client catches it by name

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

```ts title="src/client.ts (excerpt)"
const missing = yield* client.users
  .get({ params: { id: UserId.make("999") } })
  .pipe(Effect.catchTag("UserNotFound", (error) => Effect.succeed(error.message)))
```

```text title="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:

```text title="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:

```text title="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

```sh
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.

[^errors]: [`HTTPAPI.md`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/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.

[^transform]: `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`.

- **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>.
