Skip to content

Commit e9c4d68

Browse files
committed
fix: allow HTTPException reach recovery code (closes #784)
1 parent 0ea1130 commit e9c4d68

9 files changed

Lines changed: 554 additions & 24 deletions

File tree

‎docs/guide/pages-routing/errors.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,26 @@ export const loader = defineHandler((c) => c.notFound());
8282

8383
Calling `c.notFound()` in middleware invokes the app's not-found handler, which uses the root `pages/_not-found`. It doesn't select a nested boundary or run the page loader. To send your own 404 response from middleware, return a response such as `c.text('Not Found', 404)`; Void leaves it unchanged.
8484

85+
## HTTP exceptions
86+
87+
Throw an `HTTPException` with a 4xx/5xx status and a public message to show a deliberate HTTP error inside your layouts:
88+
89+
```ts
90+
// pages/account.server.ts
91+
import { HTTPException } from 'hono/http-exception';
92+
import { defineHandler } from 'void/handler';
93+
94+
export const loader = defineHandler(() => {
95+
throw new HTTPException(403, { message: 'Your account is suspended' });
96+
});
97+
```
98+
99+
The nearest `_error` receives `{ status: 403, message: 'Your account is suspended' }`. The HTML document or client-navigation response uses HTTP 403. For exceptions thrown in application middleware before the loader, Void uses the root boundary without running the loader. A 404 selects `_not-found`. If no matching boundary exists, the exception's response is returned.
100+
101+
This applies to page GET and HEAD requests. Redirects, API routes, actions, returned responses, and exceptions with an explicit `res` keep their existing behavior. Only include messages safe to show to users. Checks that determine the HTTP status must finish before deferred streaming starts.
102+
103+
Use [`c.status()`](./loaders.md#response-status) instead when you want an error status while rendering the requested page with its normal props.
104+
85105
## Nested errors
86106

87107
Put a boundary in a subdirectory to customize that section. The closest boundary wins, keeping its layout and outer layouts. A layout's own rendering failure goes to a boundary outside that layout. If an error component fails, Void tries an outer boundary, then its built-in error page.

‎packages/void/AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ Pages clients and prerender requests send `X-VoidPages: true` with `X-VoidPages-
5151

5252
Pages `_not-found`/`_error` recovery uses finite render plans that retain logical layout slots. Never serialize original exceptions through framework hydration helpers, rerun a failed loader/action, or cache an error document. Native client boundaries reset on every visit/refresh and preserve healthy ancestor layouts.
5353

54+
Recover response-less 4xx/5xx Hono `HTTPException`s only for page GET/HEAD requests: nearest boundary for loaders/handler middleware, root boundary for application middleware. Preserve redirects, explicit responses, API routes, actions, and existing 404 recovery. Middleware recovery must identify the actual matched endpoint without loading its module or replaying request code.
55+
5456
**Hono** is used as the runtime framework. The generated virtual module creates a Hono app with file-based routes and middleware. Route handlers receive a Hono `Context` object (`c`) and can use the full Hono API (`c.json()`, `c.text()`, `c.req.param()`, etc.) plus the Hono middleware ecosystem.
5557

5658
- `defineHandler(fn)` — wraps a route handler `(c: CloudContext) => R`, returns `TypedHandler<{}, R>`

‎packages/void/src/pages/protocol.ts‎

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { PAGES_PROTOCOL_VERSION } from '@void/edge';
22
import type { Context } from 'hono';
3+
import type { HTTPException } from 'hono/http-exception';
34
import { executeComposedHandler, getHandlerComposition } from '../runtime/handler-composition.ts';
45
import type { CloudBindings, CloudContext } from '../runtime/handler.ts';
56
import { isConvertedResponse } from '../runtime/response.ts';
@@ -102,6 +103,7 @@ function legacyPageResponse(
102103
c: CloudContext,
103104
errors: Record<string, string> | null = null,
104105
): Response {
106+
c.header('Cache-Control', 'no-store');
105107
const headers = pageResponseHeaders(c, {
106108
'Content-Type': errors ? 'application/json' : 'text/plain; charset=utf-8',
107109
'Cache-Control': 'no-store',
@@ -384,6 +386,38 @@ async function runLoader(
384386
});
385387
}
386388

389+
function isRecoverableHttpException(error: unknown): error is HTTPException {
390+
// Application middleware may use a different installed copy of Hono.
391+
const exception = error as HTTPException | null | undefined;
392+
return (
393+
!!exception &&
394+
typeof exception.getResponse === 'function' &&
395+
!exception.res &&
396+
typeof exception.status === 'number' &&
397+
exception.status >= 400 &&
398+
exception.status < 600
399+
);
400+
}
401+
402+
/** Recover HTTP failures outside the loader leaf without executing application code again. */
403+
export async function recoverPageHttpException(
404+
error: unknown,
405+
c: PageRequestContext,
406+
renderFn: RenderPage,
407+
getAssetTags: GetAssetTags,
408+
configHead?: HeadConfig,
409+
options?: PageRenderOptions,
410+
): Promise<Response | undefined> {
411+
if (!isRecoverableHttpException(error) || c.finalized) {
412+
return undefined;
413+
}
414+
const context = asCloudContext(c);
415+
if (options?.renderMode !== 'island' && needsPageReload(context)) {
416+
return legacyPageResponse(context);
417+
}
418+
return renderPageFailure(context, error, undefined, renderFn, getAssetTags, configHead, options);
419+
}
420+
387421
/** Recover one completed GET operation without replaying its middleware or loader. */
388422
async function renderPageFailure(
389423
c: CloudContext,
@@ -400,7 +434,11 @@ async function renderPageFailure(
400434
'getResponse' in error &&
401435
typeof error.getResponse === 'function';
402436
const explicit = httpError ? (error as { getResponse(): Response }).getResponse() : original;
403-
if (explicit && (explicit.status !== 404 || explicit.headers.has('Content-Disposition'))) {
437+
const recoverHttpError = isRecoverableHttpException(error);
438+
if (
439+
explicit &&
440+
((!recoverHttpError && explicit.status !== 404) || explicit.headers.has('Content-Disposition'))
441+
) {
404442
return undefined;
405443
}
406444
const notFound = explicit?.status === 404;
@@ -413,19 +451,22 @@ async function renderPageFailure(
413451
if (!candidates?.[0]) {
414452
return undefined;
415453
}
454+
c.header('Cache-Control', 'no-store');
416455
if (options?.renderMode !== 'island') {
417456
varyPagesResponse(c);
418457
}
419-
let status = notFound ? 404 : 500;
458+
let status = recoverHttpError ? error.status : notFound ? 404 : 500;
420459
let message = notFound
421460
? httpError && error instanceof Error
422461
? error.message || 'Not Found'
423462
: 'Not Found'
424-
: 'Internal Server Error';
425-
if (!notFound && options?.dev && error instanceof Error) {
463+
: recoverHttpError
464+
? error.message || explicit?.statusText || 'HTTP Error'
465+
: 'Internal Server Error';
466+
if (!notFound && !recoverHttpError && options?.dev && error instanceof Error) {
426467
message = error.message;
427468
}
428-
if (error && !notFound) {
469+
if (error && !notFound && !recoverHttpError) {
429470
console.error(error);
430471
}
431472
const shared = (c.get('shared') as Record<string, unknown> | undefined) ?? {};
@@ -452,7 +493,13 @@ async function renderPageFailure(
452493
errors: null,
453494
head: {
454495
...head,
455-
title: head?.title ?? (status === 404 ? 'Not Found' : 'Internal Server Error'),
496+
title:
497+
head?.title ??
498+
(status === 404
499+
? 'Not Found'
500+
: recoverHttpError && status !== 500
501+
? message
502+
: 'Internal Server Error'),
456503
},
457504
};
458505
try {

‎packages/void/src/router/compile.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ function pushDefaultErrorPageHelpers(lines: Array<string>, options: CompileOptio
2121
lines.push(
2222
`const __errorRenderer = __createErrorRenderer(${JSON.stringify({ dev: options.dev === true, projectRoot: options.projectRoot, homeDir: options.homeDir })});`,
2323
);
24-
lines.push('app.onError(__errorRenderer.onError);');
24+
lines.push('app.onError(__createPageErrorHandler(__matchedRoutes, __errorRenderer.onError));');
2525
}
2626

2727
export type AuthCompileOptions = {
@@ -196,6 +196,11 @@ export function compileRouteTable(
196196
lines.push(
197197
`import { createRoutingRuntime as __createRoutingRuntime, createHttpRouteHandler as __createHttpRouteHandler, createErrorRenderer as __createErrorRenderer, createPageGetHandler as __createPageGetHandler, createStaticNotFound as __createStaticNotFound, createPageMutationHandler as __createPageMutationHandler, createNamedActionMarker as __createNamedActionMarker, markRouteHandler as __markRouteHandler, createPagesFallback as __createPagesFallback, createModuleLoader as __createModuleLoader, createClientAssetTags as __createClientAssetTags, createManifestLoader as __createManifestLoader, createSsrFallback as __createSsrFallback, createAssetNotFound as __createAssetNotFound, buildPrerenderPath as __buildPrerenderPath } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};`,
198198
);
199+
if (pages) {
200+
lines.push(
201+
`import { createPageErrorHandler as __createPageErrorHandler } from ${JSON.stringify(ROUTING_RUNTIME_PATH)};`,
202+
);
203+
}
199204
if (options.nodeTarget) {
200205
lines.push(`const withRuntimeEnv = (_env, fn) => fn();`);
201206
} else {
@@ -306,11 +311,13 @@ export function compileRouteTable(
306311

307312
// After routing rules, which ignore the action key as platform dispatch does,
308313
// and before auth and user middleware, so their c.redirect() drops it too.
309-
if (pages && scan.pages.pages.some((page) => page.methods.includes('actions'))) {
314+
if (pages) {
310315
lines.push(
311316
`import { matchedRoutes as __matchedRoutes } from ${JSON.stringify(options.honoRoutePath)};`,
312317
);
313-
lines.push('app.use(__createNamedActionMarker(__matchedRoutes));');
318+
if (scan.pages.pages.some((page) => page.methods.includes('actions'))) {
319+
lines.push('app.use(__createNamedActionMarker(__matchedRoutes));');
320+
}
314321
}
315322

316323
const headerRules = emitEdgeRules ? options.headerRules : undefined;
@@ -1144,7 +1151,8 @@ function compilePageRoutes(
11441151
const trailingCatchAll = options.trailingSlash && page.catchAll;
11451152
const pattern = trailingCatchAll ? page.pattern.slice(0, -1) : page.pattern;
11461153
const catchAllParam = page.pattern.match(/:([^/{}]+)\{\.\+\}\/$/)?.[1];
1147-
const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`;
1154+
const middlewareBoundaries = `middlewareBoundaries: ${JSON.stringify({ notFound: boundaryManifest.root, errors: (boundaryManifest.pages[page.componentId]?.errors ?? []).filter((id) => !boundaryManifest.plans[id].directory) })}, `;
1155+
const routeOptions = `{ ${serverImportPath ? 'load: _pload_' + safeId + ', ' : ''}${mdHeadRef ? 'head: ' + mdHeadRef + ', ' : ''}${trailingCatchAll ? `trailingSlash: true, catchAllParam: ${JSON.stringify(catchAllParam)}, ` : ''}${middlewareBoundaries}componentId: ${JSON.stringify(page.componentId)}, render: ${renderer}, assets: ${assetTags}, headConfig: __voidHeadConfig, renderOptions: ${JSON.stringify({ renderMode: page.renderMode, ...(options.dev === true ? { dev: true } : {}), ...(boundaryManifest.pages[page.componentId] && { boundaries: boundaryManifest.pages[page.componentId] }) })} }`;
11481156
lines.push(`app.get(${JSON.stringify(pattern)}, __createPageGetHandler(${routeOptions}));`);
11491157
if (page.methods.includes('action') || page.methods.includes('actions')) {
11501158
lines.push(

‎packages/void/src/runtime/routing-pages.ts‎

Lines changed: 80 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
searchWithoutPreservedQuery,
66
} from '../pages/action-key.ts';
77
import { handlesPageLoaderNotFound } from '../pages/not-found-context.ts';
8-
import { handlePageGet, handlePageMutation } from '../pages/protocol.ts';
8+
import { handlePageGet, handlePageMutation, recoverPageHttpException } from '../pages/protocol.ts';
99
import { decodePagePath } from '../pages/url.ts';
1010
import type { ClientAssetTags } from './routing-assets.ts';
1111
import type { ErrorRenderer } from './routing-errors.ts';
@@ -28,6 +28,7 @@ export type PageRouteOptions = {
2828
assets: PageGetArguments[5];
2929
headConfig: PageGetArguments[6] | null;
3030
renderOptions: PageGetArguments[7];
31+
middlewareBoundaries?: NonNullable<PageGetArguments[7]>['boundaries'];
3132
namedActions?: boolean;
3233
trailingSlash?: boolean;
3334
catchAllParam?: string;
@@ -59,11 +60,61 @@ function actionNameOf(request: Request): string | undefined {
5960
}
6061
const routeHandlers = new WeakSet<Function>();
6162
const namedActionHandlers = new WeakSet<Function>();
63+
const pageGetOptions = new WeakMap<Function, PageRouteOptions>();
6264
/** Records a handler that answers a route, so the marker can tell it from middleware. */
6365
export function markRouteHandler<T extends Function>(handler: T): T {
6466
routeHandlers.add(handler);
6567
return handler;
6668
}
69+
70+
/** Hono catches middleware throws itself, before the page endpoint can run. */
71+
export function createPageErrorHandler(
72+
matchedRoutes: (c: Context) => Array<{ handler: Function }>,
73+
fallback: ErrorRenderer['onError'],
74+
): ErrorRenderer['onError'] {
75+
const recovering = new WeakSet<Context>();
76+
return async (error, c) => {
77+
if ((c.req.method !== 'GET' && c.req.method !== 'HEAD') || recovering.has(c)) {
78+
return fallback(error, c);
79+
}
80+
// Use the first endpoint, not a broad Pages pattern that follows an API route.
81+
const routes = matchedRoutes(c);
82+
const endpointIndex = routes.findIndex((route) => routeHandlers.has(route.handler));
83+
const options =
84+
endpointIndex < 0 ? undefined : pageGetOptions.get(routes[endpointIndex].handler);
85+
// The endpoint already tried its nearest boundary; do not retry it as a middleware failure.
86+
if (c.req.routeIndex >= endpointIndex) {
87+
return fallback(error, c);
88+
}
89+
if (!options || (options.trailingSlash && !c.req.path.endsWith('/'))) {
90+
return fallback(error, c);
91+
}
92+
recovering.add(c);
93+
const routeIndex = c.req.routeIndex;
94+
try {
95+
// Params are scoped to Hono's current route, which is still the failed middleware.
96+
c.req.routeIndex = endpointIndex;
97+
const response = await recoverPageHttpException(
98+
error,
99+
c,
100+
options.render,
101+
options.assets,
102+
options.headConfig ?? undefined,
103+
{ ...options.renderOptions, boundaries: options.middlewareBoundaries ?? { errors: [] } },
104+
);
105+
return response ?? fallback(error, c);
106+
} catch (failure) {
107+
return fallback(
108+
failure instanceof Error
109+
? failure
110+
: new Error('Unable to render Pages error boundary', { cause: failure }),
111+
c,
112+
);
113+
} finally {
114+
c.req.routeIndex = routeIndex;
115+
}
116+
};
117+
}
67118
/**
68119
* Runs before auth and user middleware, so a c.redirect() there leaves the
69120
* action key out too. It marks the request only when a page with named actions
@@ -86,7 +137,7 @@ export function createNamedActionMarker(
86137
};
87138
}
88139
export function createPageGetHandler(options: PageRouteOptions): (c: Context) => Promise<Response> {
89-
return markRouteHandler(async (context: Context) => {
140+
const handler = markRouteHandler(async (context: Context) => {
90141
if (!preparePageRequest(context, options)) {
91142
return context.notFound();
92143
}
@@ -100,17 +151,34 @@ export function createPageGetHandler(options: PageRouteOptions): (c: Context) =>
100151
},
101152
};
102153
}
103-
return handlePageGet(
104-
mod.loader,
105-
mod.head,
106-
context as PageGetArguments[2],
107-
options.componentId,
108-
options.render,
109-
options.assets,
110-
options.headConfig ?? undefined,
111-
options.renderOptions,
112-
);
154+
try {
155+
return await handlePageGet(
156+
mod.loader,
157+
mod.head,
158+
context as PageGetArguments[2],
159+
options.componentId,
160+
options.render,
161+
options.assets,
162+
options.headConfig ?? undefined,
163+
options.renderOptions,
164+
);
165+
} catch (error) {
166+
const response = await recoverPageHttpException(
167+
error,
168+
context,
169+
options.render,
170+
options.assets,
171+
options.headConfig ?? undefined,
172+
options.renderOptions,
173+
);
174+
if (response) {
175+
return response;
176+
}
177+
throw error;
178+
}
113179
});
180+
pageGetOptions.set(handler, options);
181+
return handler;
114182
}
115183

116184
/** Build-only rendering bypasses application middleware and serializes no request data. */

‎packages/void/src/runtime/routing.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,7 @@ export function createHttpRouteHandler(
571571

572572
export {
573573
createPageGetHandler,
574+
createPageErrorHandler,
574575
createStaticNotFound,
575576
createPageMutationHandler,
576577
createPagesFallback,

‎packages/void/test/integration/http-errors-playground.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,31 @@ describe.each(['dev', 'production'] as const)('HTTP errors playground (%s)', (mo
302302
}
303303
});
304304

305+
it.each(['/loaders/errors/403', '/middleware/errors/403'])(
306+
'navigates away from %s and restores it through history without reloading',
307+
async (path) => {
308+
await openHome();
309+
const heading = path.startsWith('/loaders/')
310+
? 'Nested error boundary'
311+
: 'Root error boundary';
312+
await page
313+
.locator(`a[href="${path}"]`)
314+
.getByText('Client navigation', { exact: true })
315+
.click();
316+
await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
317+
await page.getByRole('link', { name: 'HTTP Errors Example', exact: true }).click();
318+
await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
319+
await page.goBack();
320+
await expect.poll(() => page.locator('main h1').textContent()).toBe(heading);
321+
await page.goForward();
322+
await expect.poll(() => page.locator('main h1').textContent()).toBe('HTTP Errors Example');
323+
expect(await page.locator('header').getAttribute('data-retained')).toBe('yes');
324+
expect(await page.evaluate(() => Reflect.get(globalThis, '__HTTP_ERRORS_DOCUMENT__'))).toBe(
325+
true,
326+
);
327+
},
328+
);
329+
305330
it.each(['hover', 'focus'] as const)(
306331
'prefetches complete deferred props on %s without navigating',
307332
async (interaction) => {

0 commit comments

Comments
 (0)