Skip to content

Commit 5662bbb

Browse files
authored
Merge pull request #3481 from solidjs/server-error-hook
feat(solid,web): the server error hook — configureServerErrors / onServerError (#3468 part 3)
2 parents 37ea885 + 10401f1 commit 5662bbb

17 files changed

Lines changed: 998 additions & 60 deletions

File tree

‎.changeset/server-error-hook.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
The server error hook — `configureServerErrors({ onError })` from `@solidjs/web`, `onServerError` on `renderToStream`/`renderToString` and on `handleServerFunctionRequest`: the prod-tier seam through which a server integration hears every failure the runtime handles and may say what the client receives instead (sentry-integration-plan C6, #3468 part 3).
7+
8+
Until now a production build reported only the failure that fails a request (`renderToStream`'s `onError`); an `<Errored>` fallback rendered, a `<Loading>` fragment rejected and re-rendered by the client, and a server-function throw sanitized onto the wire were observe-tier findings only. The hook is called **once per error object, at first sight**, with where the failure was met — `kind: "render"` (`fallback` / `client` / `failed`, with the boundary's hydration id and the component labels when compiled in) or `kind: "server-function"` (`thrown` / `channel`, with `functionId` and `direct` for an in-process call during SSR) — and the request event. Its return is the **wire value**: rendered into the fallback, serialized for hydration, sent as the RPC error; `undefined` keeps the default policy (generic outside dev, fidelity in dev); ignored for `failed`. A direct server-function call that throws during SSR is reported once as the function's failure, and the boundary that contains it reuses the verdict. Two tiers as `wrapInvocation` has: ambient (registered on `globalThis` under `Symbol.for("solid-js/server/errors")`, shared by a bundled build and an `--import`ed module) and per request, the latter winning. A throwing hook is reported and treated as silent. The hook fires in every tier; `onError` keeps its meaning.
9+
10+
Internals: `solid-js`'s server entry owns the verdict engine (`reportServerError` / `ssrSanitizeError` through `solid-js/internal`, one cache per error object); the SSR context gains `errorPolicy` and `flushed`; the `_fr` rejection reads its verdict at delivery. A rejected async source's own serialized rejection is encoded in the rejection's microtask, ahead of the boundary, and carries the default policy's value — the mapping reaches the boundary's record, which the hydrating client renders from; no tick is added to the error path. `SSR_ERROR_SANITIZED` carries `data.wire`.

‎documentation/solid-2.0/08-dev-diagnostics.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -488,9 +488,9 @@ Finding (`error`, observe + dev). A server function threw and the non-dev wire r
488488

489489
#### `SSR_ERROR_SANITIZED`
490490

491-
**Message:** "[SSR_ERROR_SANITIZED] Render error replaced with a generic Error before reaching the client: TypeError: …"
491+
**Message:** "[SSR_ERROR_SANITIZED] Render error replaced before reaching the client: TypeError: …"
492492

493-
Finding (`info`, observe + dev; channel only). A render failure was about to reach the client through one of SSR's roads — the record an `<Errored>` serializes so the client hydrates the same fallback, a rejected async source serialized into the stream, a `<Loading>` fragment's `_fr` rejection, a frame stream's error chunk (the fragment's, a live hole's, the root's) — and the non-dev wire replaced it with the generic `Error` (`"Internal Server Error"`), the same policy the server-function wire applies (`SERVER_FN_ERROR_SANITIZED`; a `"use server"` function called in-process during SSR never touches that wire, so before this the page load leaked what the RPC withheld — [#3468](https://github.com/solidjs/solid/issues/3468)). The boundary sanitizes _before_ rendering its fallback and serializes the same replacement, so fallback markup and record agree on hydration. Advisory because the failure itself is the `SSR_RENDER_ERROR_CONTAINED` finding's, which carries the original; this is the record of what the wire carried instead, `data.error` the original, once per original however many roads it took. A value branded with `markSafeError` passes through and is not reported; an Error reached as a _value_ — never thrown — is data and passes as the author wrote it (#3113's ruling). The dev build keeps full fidelity.
493+
Finding (`info`, observe + dev; channel only). A render failure was about to reach the client through one of SSR's roads — the record an `<Errored>` serializes so the client hydrates the same fallback, a rejected async source serialized into the stream, a `<Loading>` fragment's `_fr` rejection, a frame stream's error chunk (the fragment's, a live hole's, the root's) — and the non-dev wire replaced it with the generic `Error` (`"Internal Server Error"`), the same policy the server-function wire applies (`SERVER_FN_ERROR_SANITIZED`; a `"use server"` function called in-process during SSR never touches that wire, so before this the page load leaked what the RPC withheld — [#3468](https://github.com/solidjs/solid/issues/3468)). The boundary sanitizes _before_ rendering its fallback and serializes the same replacement, so fallback markup and record agree on hydration. Advisory because the failure itself is the `SSR_RENDER_ERROR_CONTAINED` finding's, which carries the original; this is the record of what the wire carried instead — `data.error` the original, `data.wire` the replacement (the generic `Error`, or what the server error hook returned; [RFC 12](12-ssr-http.md#the-server-error-hook-configureservererrors--onservererror)) — once per original however many roads it took. The hook is the prod-tier seam for the same facts; these findings sit above it, recording whatever the wire actually carried. A value branded with `markSafeError` passes through and is not reported; an Error reached as a _value_ — never thrown — is data and passes as the author wrote it (#3113's ruling). The dev build keeps full fidelity.
494494

495495
#### `FRAME_MARKER_CORRUPTED`
496496

‎documentation/solid-2.0/10-server-functions.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ Framework error hooks compose the same way: a `wrapInvocation`/`transformResult`
115115

116116
The same policy covers the SSR roads a failure takes to the client — an `<Errored>` record, a rejected async source in the stream, a fragment's rejection, a frame's error chunks — so a `"use server"` function called in-process during a render (which never touches this handler) cannot ship on the page what the RPC wire withholds; see [RFC 12](12-ssr-http.md#what-a-render-failure-looks-like-from-the-client) and `SSR_ERROR_SANITIZED` in [RFC 08](08-dev-diagnostics.md#ssr_error_sanitized). `markSafeError` is the one brand on both.
117117

118+
**The server error hook** ([RFC 12](12-ssr-http.md#the-server-error-hook-configureservererrors--onservererror)) hears every failure on this wire before the policy applies — `kind: "server-function"`, `handling: "thrown"` for the body's throw, `"channel"` for a failure escaping through the result graph, `functionId` and `direct` (an in-process call during SSR) named — once per error object; its return, when given, is what the client receives. Ambient through `configureServerErrors`, per request through `handleServerFunctionRequest(request, { onServerError })` (entry-only, like `wrapInvocation`: a direct call the body makes reports through the ambient hook). A `wrapInvocation` that maps errors keeps working; the hook is where a _reporting_ integration (an error monitor) plugs in without owning invocation policy.
119+
118120
### Single-flight
119121

120122
The protocol folds integration data (typically revalidated route data) into a mutation’s response, saving a round trip. Core standardizes only the wire shape and delivery; what the data _is_ — a data-only render, route preloads, a cache query — is entirely the integration’s business.

‎documentation/solid-2.0/12-ssr-http.md‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,31 @@ A render failure reaches the client on several roads: the error an `<Errored>` c
140140

141141
The boundary sanitizes _before_ rendering its fallback, and serializes the same replacement: the fallback is rendered on the server with the error and hydrates against the record, so the two must agree. A fallback that prints `err().message` therefore shows the generic message in production, as it would for a server-function failure. `markSafeError` is the escape hatch on both wires — a branded error passes through with its own properties. An Error reached as a _value_ (never thrown — a form's field errors, say) is data and passes as written.
142142

143-
The dev/prod line is the build variant: the `development` export condition's server artifacts keep full fidelity; the production and observe artifacts sanitize. The observe tier records each replacement once as `SSR_ERROR_SANITIZED` (advisory; `data.error` the original), beside the `SSR_RENDER_ERROR_CONTAINED` finding that carries the failure itself — the server keeps the truth, the wire gets the generic.
143+
The dev/prod line is the build variant: the `development` export condition's server artifacts keep full fidelity; the production and observe artifacts sanitize. The observe tier records each replacement once as `SSR_ERROR_SANITIZED` (advisory; `data.error` the original, `data.wire` what replaced it), beside the `SSR_RENDER_ERROR_CONTAINED` finding that carries the failure itself — the server keeps the truth, the wire gets the generic.
144+
145+
#### The server error hook: `configureServerErrors` / `onServerError`
146+
147+
Everything above is what the runtime does on its own. What it _handles_ — a fallback rendered, a fragment rejected and re-rendered by the client, a server-function throw sanitized — was, until this hook, invisible to a production consumer: the observe tier records it, a prod build has no `OBSERVE`, and `renderToStream`'s `onError` hears only the failure that fails the request. The server error hook is the prod-tier seam for both **reporting** and **mapping**:
148+
149+
```ts
150+
import { configureServerErrors } from "@solidjs/web";
151+
152+
configureServerErrors({
153+
onError(error, { kind, handling, boundary, functionId, direct, ownerPath, event }) {
154+
Sentry.captureException(error, {
155+
mechanism: { type: `solid.${kind}.${handling}`, handled: handling !== "failed" }
156+
});
157+
// return nothing: the default wire policy applies
158+
// return new Error("Something went wrong"): the client receives this instead
159+
}
160+
});
161+
```
162+
163+
- **Called once per error object, at first sight**, with where the failure was met. `kind: "render"` — `fallback` (an `<Errored>` rendered its fallback; `boundary` is its hydration id, `ownerPath` the component labels when the compiler emitted them), `client` (a `<Loading>` fragment rejected, the client re-renders the subtree), `failed` (nothing contained it; the request fails, and `onError` hears it too). `kind: "server-function"` — `thrown` (the body threw; `functionId`, and `direct: true` for an in-process call during SSR) or `channel` (a rejection or throw escaping through the result graph, the head already committed). `event` is the request, when the failure happened inside one.
164+
- **The return is the wire value**: rendered into the fallback, serialized for hydration, sent as the RPC error. `undefined` leaves the default policy in place (generic outside dev, fidelity in dev). A returned value is the author's intent — like a `wrapInvocation` mapping — and is not sanitized again; `markSafeError` is not needed on it. Ignored for `failed`, which has no wire.
165+
- **Once means once across roads.** A direct server-function call that throws during SSR is met first by the invocation (`kind: "server-function"`, `direct: true`) and then by the `<Errored>` that contains it; the boundary reuses the verdict — the same replacement in the fallback and the record — and does not report again. A `<Loading>` re-pull recurring the same throw is the same object, the same verdict. The observe tier keeps the multi-event picture (an `"invocation"` record _and_ an `SSR_RENDER_ERROR_CONTAINED` finding) for consumers that want it.
166+
- **Two tiers, as `wrapInvocation` has.** Ambient: `configureServerErrors({ onError })`, once per process, registered on `globalThis` under a registered symbol so a bundled server build and an instrumented `--import`ed module share it — and the only tier that sees direct in-process calls. Per request, overriding it: `renderToStream(code, { onServerError })` / `renderToString(code, { onServerError })`, and `handleServerFunctionRequest(request, { onServerError })` for the call it dispatches. A throwing hook is reported on the console and treated as silent.
167+
- **Where it runs.** The hook fires in every tier — dev included (an error monitor in development is ordinary); only the _default_ mapping differs by tier. `onError` on `renderToStream` keeps its meaning — the request failed — unchanged.
144168

145169
### The trace the request belongs to: `getTraceContext()`
146170

‎packages/solid/skills/reactivity-diagnostics/SKILL.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,11 @@ production wire replaced it with the generic `Error`; `data.error` is the
503503
original. Advisory: the failure itself is the `SSR_RENDER_ERROR_CONTAINED`
504504
finding beside it — fix that. If the client is meant to see this error, brand
505505
it with `markSafeError`; do not turn sanitization off. A fallback that prints
506-
`err().message` shows "Internal Server Error" in production by design.
506+
`err().message` shows "Internal Server Error" in production by design. To
507+
_report_ these failures from a production build (no `OBSERVE`), register the
508+
server error hook — `configureServerErrors({ onError })` from `@solidjs/web`
509+
— which hears every handled failure once, and may return the value the client
510+
should see instead.
507511

508512
### FRAME_MARKER_CORRUPTED
509513

‎packages/solid/src/index.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,22 @@ export function inServerComponentScope(): boolean {
136136
export function ssrSanitizeError(value: unknown): unknown {
137137
return value;
138138
}
139+
/** @internal — server-only: the server error hook has no client half here. */
140+
export function reportServerError(): { mapped: boolean; value?: unknown } {
141+
return { mapped: false };
142+
}
143+
/** Where a server failure was met, as the server error hook hears it (see `@solidjs/web`'s `ServerErrorContext`). */
144+
export interface ServerErrorSite {
145+
kind: "render" | "server-function";
146+
handling: "fallback" | "client" | "failed" | "thrown" | "channel";
147+
boundary?: string;
148+
ownerPath?: string[];
149+
functionId?: string;
150+
direct?: boolean;
151+
/** The request event, when the caller has it in hand; else read from the request scope. */
152+
event?: unknown;
153+
}
154+
export type ServerErrorHook = (error: unknown, context: ServerErrorSite) => unknown | void;
139155
/** @internal — server-only: on the client no value carries a trace. */
140156
export function getProjectionTrace(
141157
value: unknown

‎packages/solid/src/internal.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
* entries mark them `@internal` and strip them from their declarations.
2525
*/
2626
import * as core from "solid-js";
27+
import type { ServerErrorHook, ServerErrorSite } from "solid-js";
2728

2829
export {
2930
mergeSources,
@@ -68,8 +69,26 @@ export const inServerComponentScope: () => boolean = core.inServerComponentScope
6869
* (recorded once as `SSR_ERROR_SANITIZED`). `subject` locates the finding;
6970
* `null` from a serialization funnel. Client: identity.
7071
*/
71-
export const ssrSanitizeError: (value: unknown, subject?: object | null) => unknown =
72-
core.ssrSanitizeError;
72+
export const ssrSanitizeError: (
73+
value: unknown,
74+
subject?: object | null,
75+
site?: ServerErrorSite
76+
) => unknown = core.ssrSanitizeError;
77+
78+
/**
79+
* Server: tells the server error hook about a failure — once per error
80+
* object, at first sight — with where it was met; `{ mapped: true, value }`
81+
* when the hook gave a wire value (now or earlier), `{ mapped: false }`
82+
* otherwise. `hook` is a per-request override ahead of the SSR context's
83+
* `errorPolicy` and the ambient registration. Client: `{ mapped: false }`.
84+
*/
85+
export const reportServerError: (
86+
value: unknown,
87+
site: ServerErrorSite,
88+
subject?: object | null,
89+
hook?: ServerErrorHook
90+
) => { mapped: boolean; value?: unknown } = core.reportServerError as any;
91+
export type { ServerErrorSite, ServerErrorHook } from "solid-js";
7392

7493
/** Server: a monotonic stamp for owner creation order. Client: `0`. */
7594
export const creationStamp: () => number = core.creationStamp;

‎packages/solid/src/server/hydration.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import {
99
getContext,
1010
setContext,
1111
runWithBoundaryErrorContext,
12-
RevealGroupContext
12+
RevealGroupContext,
13+
reportServerError
1314
} from "./signals.js";
1415
import { OBSERVE, ownerPath } from "@solidjs/signals";
1516
import { sharedConfig, NoHydrateContext } from "./shared.js";
@@ -286,6 +287,10 @@ function ssrLoadingBoundary(
286287
// fallback expecting server DOM that was never emitted, derailing
287288
// hydration before the fragment channel can engage.
288289
reportRouted(err, "client");
290+
// The server error hook hears of it here, before the channel
291+
// carries it (the `_fr` rejection, a transport sink's error chunk
292+
// read the verdict the hook decides).
293+
reportServerError(err, { kind: "render", handling: "client", boundary: id }, o);
289294
streamedOnError = done(undefined, err);
290295
throw err;
291296
}
@@ -321,8 +326,15 @@ function ssrLoadingBoundary(
321326
return;
322327
}
323328
if (done) {
324-
const streamed = done(undefined, err);
325-
if (streamed) {
329+
// Post-flush the fragment rejects to the client: the server error hook
330+
// hears of it BEFORE the channel carries it, so the `_fr` rejection and
331+
// a transport sink's error chunk read the verdict it decides. Pre-flush
332+
// the rejection reaches the client lazily (the funnel reads the verdict
333+
// when it delivers) and the failure is met next by the parent handler
334+
// — an <Errored> rendering its fallback — or fails the request below.
335+
const streamed = ctx.flushed !== undefined && ctx.flushed();
336+
if (streamed) reportServerError(err, { kind: "render", handling: "client", boundary: id }, o);
337+
if (done(undefined, err)) {
326338
reportRouted(err, "client");
327339
record("error", true, err);
328340
return;
@@ -331,6 +343,7 @@ function ssrLoadingBoundary(
331343
record("error", false, err);
332344
if (!parentHandler) {
333345
reportRouted(err, "failed");
346+
reportServerError(err, { kind: "render", handling: "failed", boundary: id }, o);
334347
ctx.failRender ? ctx.failRender(err) : console.error(err);
335348
return;
336349
}
@@ -339,6 +352,7 @@ function ssrLoadingBoundary(
339352
} catch (caught) {
340353
if (caught !== err) {
341354
reportRouted(caught, "failed");
355+
reportServerError(caught, { kind: "render", handling: "failed", boundary: id }, o);
342356
ctx.failRender ? ctx.failRender(caught) : console.error(caught);
343357
}
344358
}

‎packages/solid/src/server/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,10 @@ export {
140140
runInServerComponentScope,
141141
inServerComponentScope,
142142
getProjectionTrace,
143-
ssrSanitizeError
143+
ssrSanitizeError,
144+
reportServerError
144145
} from "./signals.js";
146+
export type { ServerErrorSite, ServerErrorHook } from "./signals.js";
145147
/** @internal */
146148
export { ssrHandleError, ssrScope } from "./hydration.js";
147149

‎packages/solid/src/server/shared.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ export type HydrationContext = {
7373
* process survives.
7474
*/
7575
failRender?: (err: any) => void;
76+
/**
77+
* @internal The per-request server error hook (`renderToStream`'s
78+
* `onServerError`), set by @solidjs/web; consulted by `reportServerError`
79+
* ahead of the ambient registration.
80+
*/
81+
errorPolicy?: (error: unknown, context: any) => unknown | void;
82+
/**
83+
* @internal Whether the shell has flushed — a fragment that fails now
84+
* rejects to the client (`handling: "client"`) rather than failing the
85+
* request or inlining into a parent's fallback. Set by @solidjs/web's
86+
* renderToStream.
87+
*/
88+
flushed?: () => boolean;
7689
/**
7790
* @internal Per-request memo of `resolveAssets(moduleUrl)` results, keyed
7891
* by moduleUrl. lazy() consults it so a component re-created across

0 commit comments

Comments
 (0)