Files
core/src/transformers.ts
T
chrnx ee5f84aa61
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 19s
CI / build (pull_request) Successful in 30s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s
fix(transformers)!: answer 204 when a handler returns undefined (GitHub #38)
JsonTransformer passed the handler's value to JSON.stringify, which
returns undefined for undefined, while TransformerFn promises a string
body. The Node server wrote that as an empty 200 with content-type
application/json; the fetch adapter's toBodyInit read `body.buffer` on
it and threw, so Deno, Bun and the edge answered 500 for a handler with
no `return`.

JsonTransformer now returns status 204 and an empty body (no headers)
for undefined. outcomeToResponse already sends a null body for 204 and
the Node server ends with the empty string, so all four runtimes give
the same answer. null is a JSON value and still renders as 200 `null`.
Routes with their own @Transformer are unchanged.

BREAKING CHANGE: a handler with no return value now answers 204 instead
of an empty 200 on Node (and instead of 500 elsewhere). Return a value
to keep a 200.

test/undefined-return.test.ts covers app.fetch and the Node server
(both fail without the fix) and pins null to 200.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 22:23:27 -05:00

96 lines
3.9 KiB
TypeScript

import { isHttpError, isValidationError } from './signals';
import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */
export interface ErrorResponse {
status: number;
/** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string;
}
/** The request a {@link ErrorRenderer} is given, to inspect (e.g. `headers.accept`) while rendering. */
export interface ErrorRequest {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}
/**
* User hook to render errors however you like (HTML, custom JSON, RFC 7807, …).
* Return a response to take over, or `undefined`/`void` to fall back to the default JSON.
*/
export type ErrorRenderer = (error: unknown, req: ErrorRequest) => ErrorResponse | undefined | void;
/**
* Default transformer: serialize a handler's return value as a JSON `200` response. A handler that
* returns `undefined` (no `return`) answers `204 No Content` with no body, on every runtime (GitHub #38).
*/
export const JsonTransformer: TransformerFn = (value) => {
if (value === undefined) return { status: 204, body: '' };
return { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) };
};
/**
* Map a thrown value to a JSON error response (422 for validation, `HttpError` status, else 500).
* An `HttpError` carrying a `body` renders that payload instead of the default `{ error: message }`.
*/
export function errorToResponse(error: unknown): ErrorResponse {
if (isValidationError(error)) {
return {
status: 422,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
error: 'Validation failed',
source: error.source,
issues: error.issues.map((issue) => ({ path: flattenPath(issue), message: issue.message })),
}),
};
}
if (isHttpError(error)) {
const headers = { 'content-type': 'application/json', ...error.headers };
const payload = error.body !== undefined ? error.body : { error: error.message };
return { status: error.status, headers, body: JSON.stringify(payload) };
}
return {
status: 500,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ error: 'Internal Server Error' }),
};
}
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(
error: unknown,
req: ErrorRequest,
onError?: ErrorRenderer,
logger?: Logger,
): ErrorResponse {
if (!onError) return errorToResponse(error);
// `onError` is user code, it runs on the request path, and it runs *after something already went
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
// occurs, the code written to report it fails, and the process ends instead of degrading.
//
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
// custom renderer and no matching route is one request away from exiting.
//
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
// overrides and therefore the honest thing to fall back to: the original error still gets its
// response. The renderer's own failure is reported separately, because it is a different error
// from the request's and a reader chasing the wrong one loses an afternoon.
try {
return onError(error, req) ?? errorToResponse(error);
} catch (rendererError) {
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
rendering: error instanceof Error ? error.message : String(error),
});
return errorToResponse(error);
}
}