feat: per-route body limits, custom error rendering, OpenAPI generation
CI / build (push) Has been cancelled

Three capabilities that share the same request/route metadata:

- **Per-route upload limits** — `@Post('/x', { maxBodyBytes, maxParts })`
  overrides the server-wide `limits` for one route (falls back to the
  global default), mirroring the existing per-route `duplicates`.

- **Custom error rendering** — `createApp({ onError })` takes over how any
  error becomes a response (HTML, RFC 7807, content-negotiated), covering
  the whole surface: handler/step throws, 404, 405, 413, 400. Returns a
  response or undefined to fall back to the default JSON. Also wires the
  previously-unused `HttpError` `body` field so `throw new HttpError(409,
  'conflict', { code })` renders a structured payload. Default behavior is
  unchanged when no hook is set.

- **OpenAPI 3.1** — `app.openapi(info?)` projects the route graph into a
  structural spec (paths, methods, path/query/header params, request-body
  presence, systematic error responses); opt-in `GET /__openapi__` via
  `devOpenapi`. Body/response schemas stay generic (Standard Schema exposes
  no JSON Schema) — the full `@Produce` mode is post-beta.

Docs: new error-handling and OpenAPI guides, plus reference updates.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-08 08:29:17 -05:00
1 parent 7c20d74fe4
commit 2db5de6858
19 files changed
+811 -100

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
---
title: Error handling
description: "Throw typed errors anywhere; render them however you like with onError."
---
Errors are **thrown, not returned**. Throw a typed error anywhere in the pipeline — a provider, a step, or a handler — and green-tea converts it to a response at one place.
## The typed errors
All live in `@green-tea/core`:
| Throw | Status |
|---|---|
| `Unauthorized(msg?)` | `401` |
| `NotFound(msg?)` | `404` |
| `NotModified()` | `304` |
| `Redirect(location)` | `302` + `Location` |
| `ValidationError` | `422` (raised for you by schema validation) |
| `HttpError(status, msg?, body?)` | any status |
| anything else | `500` (message hidden — internals never leak) |
```typescript
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('invalid token'); // → 401, cuts the request
return { user };
}
}
```
By default an error becomes JSON: `{ "error": "<message>" }` (validation adds `source` + per-field `issues`).
## Structured error bodies
An `HttpError` can carry a **body** — return a structured payload instead of the default `{ error }`:
```typescript
throw new HttpError(409, 'conflict', { code: 'DUP_EMAIL', field: 'email' });
// → 409 { "code": "DUP_EMAIL", "field": "email" }
```
## Render errors your way — `onError`
Not everything should be JSON. Pass `onError` to `createApp` to render errors however you like — HTML, [RFC 7807](https://www.rfc-editor.org/rfc/rfc7807), content-negotiated, anything. It receives the error and the request, and returns a response — or `undefined` to fall back to the default JSON.
```typescript
import { isHttpError } from '@green-tea/core';
const app = createApp({
modules: [ApiModule],
onError(error, req) {
const status = isHttpError(error) ? error.status : 500;
// negotiate: HTML for browsers, JSON for API clients
if (String(req.headers.accept).includes('text/html')) {
return { status, headers: { 'content-type': 'text/html' }, body: `<h1>${status}</h1>` };
}
return undefined; // fall back to the default JSON
},
});
```
`onError` intercepts **every** HTTP error response — handler/step throws, a `404` for an unmatched route, `405`, a `413` (body too large), and a `400` (malformed body) — so your error surface is consistent across the whole app. Streaming and WebSocket errors are out of scope (they surface as an error frame or a WebSocket close code, not a response body).
:::note
Errors are also observable without changing the response: subscribe to `request:step:error` (and `stream:error`) on [`app.bus`](/guides/plugins/) to log or trace them.
:::
@@ -0,0 +1,41 @@
---
title: OpenAPI
description: "Generate a structural OpenAPI 3.1 document from the route graph."
---
Because the request pipeline is [data you can read](/concepts/the-graph/), green-tea can project it — the same way it renders [Mermaid/DOT](/guides/introspection/), it emits **OpenAPI**.
## `app.openapi()`
```typescript
const app = createApp({ modules: [ApiModule] });
const spec = app.openapi({ title: 'My API', version: '1.0.0' });
// → OpenAPI 3.1 document
```
It reads the routes and handler signatures and produces, for each route:
- the **path**, templated — `/users/:id` → `/users/{id}`, catch-all `:path*` → `{path}`;
- the **method**;
- **parameters** — path params from the pattern, plus query/header params from the handler's `@query` / `@headers` / `@header` decorators;
- a **request body** entry for routes that read `@body()`;
- the systematic **responses** — `200`, a `422` when any argument is schema-validated, and `500`.
WebSocket routes are omitted (they aren't request/response).
## Serve it — `devOpenapi`
Opt in to a `GET /__openapi__` endpoint that returns the document as JSON — point Swagger UI, Redoc, or a codegen client at it:
```typescript
const app = createApp({ modules: [ApiModule], devOpenapi: true });
// GET /__openapi__ → application/json
```
## What's structural (and what isn't yet)
This is a **structural** spec: paths, methods, parameters, which routes take a body, and the standard error responses. What it does **not** include yet:
- **Request/response body schemas.** [Standard Schema](/guides/validation/) (zod/valibot/arktype) validates input but does not expose a JSON Schema representation, so body shapes are documented generically. Parameter types default to `string`.
Full schemas — declared and enforced on the way out via a `@Produce(schema)` decorator that also validates responses — are on the roadmap for the stable release. For beta, the structural document already drives Swagger UI, client codegen, and API diffing.
+8 -1
View File
@@ -57,7 +57,14 @@ Uploaded files are held in memory, so they're bounded by the same `maxBodyBytes`
const app = createApp({ modules: [ApiModule], limits: { maxParts: 500 } });
```
A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
Both limits can be overridden **per route** — an upload endpoint can allow a larger body than the rest of the API:
```typescript
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 })
uploadAvatar(@body() form: MultipartBody) { /* ... */ }
```
A route's `maxBodyBytes` / `maxParts` fall back to the server-wide `limits` when unset. A malformed multipart body (bad boundary, missing headers, truncated part) → **400**.
:::note
To validate parsed fields against a schema, pass a Standard Schema to `@body()` — see [validation](/guides/validation/).
@@ -15,12 +15,14 @@ const app = createApp(options);
| `plugins` | `Plugin[]` | `[]` | plugins, each limited to `bus.on` + `scope.add` ([plugins](/guides/plugins/)) |
| `limits` | `RequestLimits` | see below | body-size and timeout ceilings |
| `devGraph` | `boolean` | `false` | mount `GET /__graph__` ([introspection](/guides/introspection/)) |
| `devOpenapi` | `boolean` | `false` | mount `GET /__openapi__` serving the [OpenAPI](/guides/openapi/) document |
| `overrides` | `Record<string, unknown>` | — | swap any node by token ([testing](/guides/testing/)) |
| `tls` | `TlsOptions` | — | serve over https/wss |
| `trustProxy` | `boolean` | `false` | honor `X-Forwarded-*` for `ctx.protocol` / `ctx.ip` |
| `security` | `boolean \| SecurityOptions` | `true` | secure-by-default headers ([security](/guides/security/)) |
| `cors` | `CorsOptions` | — | CORS handling |
| `bodyDuplicates` | `'array' \| 'last'` | `'last'` | policy for repeated form fields |
| `onError` | `ErrorRenderer` | — | render errors your way ([error handling](/guides/errors/)); returns a response or `undefined` to fall back to JSON |
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/guides/mesh/)) |
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
@@ -62,6 +64,7 @@ const app = createApp(options);
| `explain(route)` | `Explain` | the chain annotated with each node's needs/provides |
| `graph()` | `GraphView` | the full node + route graph |
| `toMermaid()` / `toDOT()` | `string` | render the graph |
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/guides/openapi/)) |
| `degraded()` | `string[]` | optional providers running degraded (empty until `listen()`) |
| `bus` | `Bus` | lifecycle + request event bus |
@@ -48,7 +48,7 @@ Method decorator. Turns a handler's return value into `{ status?, headers?, body
## Routes
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last' }`.
Method decorators on a controller. All accept `(path, opts?)` where `opts = { export?: boolean, duplicates?: 'array' | 'last', maxBodyBytes?: number, maxParts?: number }`. `maxBodyBytes` / `maxParts` override the server-wide [`limits`](/reference/createapp/) for this route only.
| Decorator | Method | Transport |
|---|---|---|
@@ -58,8 +58,9 @@ Method decorators on a controller. All accept `(path, opts?)` where `opts = { ex
| `@Stream` | GET | negotiated (SSE / ndjson / WS) |
```typescript
@Get('/ping', { export: true }) // exportable over mesh
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
@Get('/ping', { export: true }) // exportable over mesh
@Post('/upload', { duplicates: 'array' }) // repeated form fields → arrays
@Post('/avatar', { maxBodyBytes: 5_000_000, maxParts: 20 }) // per-route upload limits
```
See [Routing](/guides/routing/) for pattern matching and [Streaming](/guides/streaming/) for the transports.