fix(errors): an onError that throws degrades to the built-in renderer

`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.

This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.

It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.

All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — 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; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.

Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.

`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.

Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.

Closes #80.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-09-01 10:35:03 -05:00
1 parent 3930804fb3
commit 5294e62a5a
10 files changed
+153 -21

No files matched your search

+8 -4
View File
@@ -86,6 +86,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[]; planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus; bus: Bus;
onError?: ErrorRenderer; onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
} }
/** /**
@@ -229,7 +231,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
let meshControl: MeshControl | undefined; let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -306,7 +308,7 @@ export function createApp(opts: {
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
routePlans, routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError }, { providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts, fetchOpts,
bootApp, bootApp,
devRoutes, devRoutes,
@@ -1006,7 +1008,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined; if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps; const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError } = deps.deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
@@ -1045,6 +1047,7 @@ function buildMeshControl(
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
correlation: { correlation: {
requestId: env.correlation?.requestId, requestId: env.correlation?.requestId,
@@ -1070,7 +1073,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ /** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError } = deps; const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -1089,6 +1092,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete // `route` is the pattern, never req.url — a metrics consumer labelling on concrete
// paths gets one label per distinct URL, and that takes down the metrics backend. // paths gets one label per distinct URL, and that takes down the metrics backend.
+1 -1
View File
@@ -129,7 +129,7 @@ function parseAcquired(
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) => return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed 'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) } ? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body }, : { body: parsed.body },
); );
} }
+2 -2
View File
@@ -144,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, req, opts?.onError); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: {
@@ -392,7 +392,7 @@ async function dispatch(
traceId: req.traceId, traceId: req.traceId,
}); });
} catch (error) { } catch (error) {
result = renderError(error, req, opts?.onError); result = renderError(error, req, opts?.onError, opts?.logger);
} }
if (isStreamResult(result)) { if (isStreamResult(result)) {
+1 -1
View File
@@ -198,7 +198,7 @@ function readRequestBytes(
return readBodyBytes(req, limit).then( return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }), (bytes) => ({ bytes }),
(error: unknown) => { (error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError); const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } }; return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
}, },
); );
+1 -1
View File
@@ -77,7 +77,7 @@ function readFetchBytes(
url: url.pathname + url.search, url: url.pathname + url.search,
headers: headersToRecord(request.headers), headers: headersToRecord(request.headers),
}; };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) }; return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
} }
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) }; return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
+12 -6
View File
@@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel'; import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata'; import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals'; import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ /** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep { export interface PipelineStep {
@@ -113,9 +114,10 @@ export async function runPipeline(args: {
bus: Bus; bus: Bus;
transport: Transport; transport: Transport;
onError?: ErrorRenderer; onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation; correlation?: Correlation;
}): Promise<PipelineResult> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args; const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed }; let context: any = { ...seed };
@@ -145,6 +147,7 @@ export async function runPipeline(args: {
error, error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, { method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError, onError,
logger,
); );
status = rendered.status; status = rendered.status;
return rendered; return rendered;
@@ -153,11 +156,14 @@ export async function runPipeline(args: {
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is // this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where. // what produces a trace that says a request failed without saying where.
// //
// Emitted from `finally`, after the render rather than before it, for two reasons. The status // Emitted after the render rather than before it, because the status is only decided there:
// is only decided by the render — `onError` may turn any throw into any status, so deriving // `onError` may turn any throw into any status, so deriving one from the error would be a
// it from the error would be a guess that a custom renderer makes wrong. And a renderer that // guess that a custom renderer makes wrong.
// *throws* must not swallow the event: `finally` still fires, with `status` left undefined, //
// which is the one case where this event has none. // In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed')) if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation }); bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
} }
+29 -2
View File
@@ -1,6 +1,7 @@
import { isHttpError, ValidationError } from './signals'; import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { export interface ErrorResponse {
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
} }
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */ /** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { export function renderError(
return onError?.(error, req) ?? errorToResponse(error); 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);
}
} }
+73
View File
@@ -80,3 +80,76 @@ describe('HttpError body', () => {
server.close(); server.close();
}); });
}); });
// `onError` is user code, on the request path, running *after something already went wrong*. An
// unguarded throw here was 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 was also easy to
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
// route was one request away from exiting.
describe('an onError that throws', () => {
const exploding: ErrorRenderer = () => {
throw new Error('renderer exploded');
};
@Route('/x')
class Boom {
@Get('/boom') boom() {
throw new HttpError(503, 'Service Unavailable');
}
}
@Module({ mountpoint: '/', controllers: [Boom] })
class BoomModule {}
it('falls back to the built-in rendering rather than losing the response', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/x/boom'));
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
});
// The path that needed no thrown handler at all.
it('survives a 404, which the renderer also produces', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/nothing-here'));
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
});
it('reports the renderer as the thing that failed, not the request', async () => {
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
const logger = {
debug() {},
info() {},
warn() {},
error(msg: string, fields?: Record<string, unknown>) {
logged.push({ msg, fields });
},
};
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
await app.fetch(new Request('http://x/x/boom'));
expect(logged).toHaveLength(1);
expect(logged[0].msg).toMatch(/onError/);
// Both errors named, because a reader chasing the wrong one loses an afternoon.
expect(logged[0].fields?.err).toBe('renderer exploded');
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
});
it('answers over a real Node server instead of exiting the process', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const server = await app.listen(0);
const port = (server.address() as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
expect(res.status).toBe(503);
// Still serving — the point of the whole test.
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
await app.close();
});
});
+8 -4
View File
@@ -216,8 +216,9 @@ describe('failure reporting', () => {
}); });
// A renderer that throws must not swallow the event — the failure still happened, and losing the // A renderer that throws must not swallow the event — the failure still happened, and losing the
// only record of it because the reporting of it broke is the worst possible trade. // only record of it because the reporting of it broke is the worst possible trade. The status is
it('still reports the failure when onError itself throws, with no status to give', async () => { // the built-in renderer's, since that is what the request actually got.
it('still reports the failure when onError itself throws', async () => {
const app = createApp({ const app = createApp({
modules: [BadModule], modules: [BadModule],
onError: () => { onError: () => {
@@ -227,10 +228,13 @@ describe('failure reporting', () => {
const failures: EventPayload[] = []; const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p)); app.bus.on('request:failed', (p) => failures.push(p));
await app.fetch(new Request('http://x/bad/go')).catch(() => undefined); const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(500);
expect(failures).toHaveLength(1); expect(failures).toHaveLength(1);
expect(failures[0].status).toBeUndefined(); expect(failures[0].status).toBe(500);
// The request's error, not the renderer's — they are different errors and the event names the
// one the request suffered.
expect((failures[0].error as Error).message).toBe('step exploded'); expect((failures[0].error as Error).message).toBe('step exploded');
}); });
}); });
+18
View File
@@ -19,6 +19,24 @@ class Views {
class M {} class M {}
const app = createApp({ modules: [M], views: dir }); const app = createApp({ modules: [M], views: dir });
// Checked alongside the `onError` guard: `viewEngine` is the other user callback on a render path,
// and whether it had a boundary was not something to assume. It does — the pipeline's own catch
// covers it, so a broken engine is a 500 rather than a dead process. Asserted so it stays that way.
describe('a viewEngine that throws', () => {
it('renders a 500 instead of escaping the request', async () => {
const broken = createApp({
modules: [M],
views: dir,
viewEngine: () => {
throw new Error('engine exploded');
},
});
const res = await broken.fetch(new Request('http://x/user'));
expect(res.status).toBe(500);
expect(await res.json()).toEqual({ error: 'Internal Server Error' });
});
});
describe('@Html modes', () => { describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => { it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str')); const res = await app.fetch(new Request('http://x/str'));