Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions integration/rsc-server-error-logging-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { test, expect } from "@playwright/test";

import { createFixture, js } from "./helpers/create-fixture.js";
import type { Fixture } from "./helpers/create-fixture.js";

// These tests use the `rsc-vite-framework` template without custom
// `entry.rsc.tsx` / `entry.ssr.tsx` files, so they exercise the default RSC
// Framework Mode entries in `@react-router/dev/config/default-rsc-entries`.

test.describe("RSC Framework: server error logging", () => {
let fixture: Fixture;
let originalConsoleError: typeof console.error;
let logged: unknown[][];

test.beforeAll(async () => {
fixture = await createFixture({
templateName: "rsc-vite-framework",
files: {
"app/root.tsx": js`
import { Links, Meta, Outlet, ScrollRestoration } from "react-router";

export function Layout({ children }) {
return (
<html lang="en">
<head>
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
</body>
</html>
);
}

export default function App() {
return <Outlet />;
}
`,
"app/routes/loader-error.tsx": js`
export function loader() {
throw new Error("LOADER_ERROR_MESSAGE");
}

export default function LoaderError() {
return <h1>LOADER_ERROR_ROUTE</h1>;
}

export function ErrorBoundary() {
return <h1>CUSTOM_ERROR_BOUNDARY</h1>;
}
`,
"app/routes/default-boundary.tsx": js`
export function loader() {
throw new Error("DEFAULT_BOUNDARY_ERROR_MESSAGE");
}

export default function DefaultBoundaryRoute() {
return null;
}
`,
"app/routes/render-error.tsx": js`
export default function RenderErrorRoute() {
throw new Error("SSR_RENDER_ERROR_MESSAGE");
}
`,
"app/routes/resource-error.tsx": js`
export function loader() {
throw new Error("RESOURCE_ERROR_MESSAGE");
}
`,
},
});
});

// The fixture's request helpers run the built server handler in this
// process, so we can observe what it logs
test.beforeEach(() => {
logged = [];
originalConsoleError = console.error;
console.error = (...args: unknown[]) => {
logged.push(args);
};
});

test.afterEach(() => {
console.error = originalConsoleError;
});

function expectLoggedOnce(message: string) {
let messages = logged
.flat()
.map((arg) => (arg instanceof Error ? arg.message : String(arg)));
expect(messages.filter((entry) => entry.includes(message))).toHaveLength(1);
}

test("logs errors thrown from loaders", async () => {
let response = await fixture.requestDocument("/loader-error");
expect(response.status).toBe(500);
expect(await response.text()).toContain("CUSTOM_ERROR_BOUNDARY");
expectLoggedOnce("LOADER_ERROR_MESSAGE");
});

test("logs a loader error once when rendering the default root boundary", async () => {
let response = await fixture.requestDocument("/default-boundary");
expect(response.status).toBe(500);
expect(await response.text()).toContain("Application Error");
expectLoggedOnce("DEFAULT_BOUNDARY_ERROR_MESSAGE");
});

test("logs an SSR render error from the default root boundary", async () => {
let response = await fixture.requestDocument("/render-error");
expect(response.status).toBe(500);
expect(await response.text()).toContain("Application Error");
expectLoggedOnce("SSR_RENDER_ERROR_MESSAGE");
});

test("logs errors thrown from resource routes", async () => {
let response = await fixture.requestResource("/resource-error");
expect(response.status).toBe(500);
await response.text();
expectLoggedOnce("RESOURCE_ERROR_MESSAGE");
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Report loader, action, and middleware errors through `unstable_matchRSCServerRequest`'s `onError` and log request errors with `console.error` by default when no `onError` is provided

- Report middleware errors that occur after a form action consumes the request body.
- Avoid logging route errors again when rendering the default error boundary during SSR in RSC Data and RSC Framework Mode.
200 changes: 199 additions & 1 deletion packages/react-router/__tests__/rsc/server-test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from "react";
import { renderToReadableStream } from "react-dom/server.edge";
import { renderToString } from "react-dom/server.node";

import {
Expand All @@ -7,7 +8,10 @@ import {
type RSCMatch,
type RSCRouteConfigEntry,
} from "../../lib/rsc/server.rsc";
import { routeRSCServerRequest } from "../../lib/rsc/server.ssr";
import {
RSCStaticRouter,
routeRSCServerRequest,
} from "../../lib/rsc/server.ssr";
import { URL_LIMIT } from "../../lib/dom/ssr/fog-of-war";

describe("RSC server", () => {
Expand Down Expand Up @@ -663,6 +667,200 @@ describe("RSC server", () => {
expect((await payload.patches).map((patch) => patch.id)).toEqual(["other"]);
expect(routeDiscovery.mode).toBe("lazy");
});

describe("error reporting", () => {
let consoleError: jest.SpyInstance;
let abortController: AbortController;

beforeEach(() => {
consoleError = jest.spyOn(console, "error").mockImplementation(() => {});
abortController = new AbortController();
});

afterEach(() => {
consoleError.mockRestore();
});

let routes: RSCRouteConfigEntry[] = [
{
id: "root",
path: "/",
Component: () => null,
ErrorBoundary: () => null,
children: [
{
id: "loader-error",
path: "loader-error",
Component: () => null,
loader() {
throw new Error("LOADER_ERROR");
},
},
{
id: "action-error",
path: "action-error",
Component: () => null,
action() {
throw new Error("ACTION_ERROR");
},
},
{
id: "middleware-error",
path: "middleware-error",
Component: () => null,
middleware: [
() => {
throw new Error("MIDDLEWARE_ERROR");
},
],
},
{
id: "post-middleware-error",
path: "post-middleware-error",
Component: () => null,
async action({ request }) {
await request.formData();
return null;
},
middleware: [
async (_, next) => {
await next();
throw new Error("POST_MIDDLEWARE_ERROR");
},
],
},
{
id: "thrown-response",
path: "thrown-response",
Component: () => null,
loader() {
throw new Response("Nope", { status: 401 });
},
},
{
id: "aborted-resource",
path: "aborted-resource",
loader() {
abortController.abort();
throw new Error("ABORTED_ERROR");
},
},
],
},
];

function match(request: Request, onError?: (error: unknown) => void) {
return matchRSCServerRequest({
createTemporaryReferenceSet: () => ({}),
request,
routes,
onError,
generateResponse(match) {
return new Response(null, { status: match.statusCode });
},
});
}

test.each([
["loader", new Request("https://remix.run/loader-error"), "LOADER_ERROR"],
[
"action",
new Request("https://remix.run/action-error", {
method: "POST",
body: new URLSearchParams({ a: "b" }),
}),
"ACTION_ERROR",
],
[
"middleware",
new Request("https://remix.run/middleware-error"),
"MIDDLEWARE_ERROR",
],
[
"post-form-action middleware",
new Request("https://remix.run/post-middleware-error", {
method: "POST",
body: new URLSearchParams({ a: "b" }),
}),
"POST_MIDDLEWARE_ERROR",
],
])("calls onError with %s errors", async (_, request, message) => {
let onError = jest.fn();
let response = await match(request, onError);
expect(response.status).toBe(500);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(new Error(message));
});

test("does not call onError with thrown responses", async () => {
let onError = jest.fn();
let response = await match(
new Request("https://remix.run/thrown-response"),
onError,
);
expect(response.status).toBe(401);
expect(onError).not.toHaveBeenCalled();
});

test("logs errors with console.error when no onError is provided", async () => {
await match(new Request("https://remix.run/loader-error"));
expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(new Error("LOADER_ERROR"));
});

test("logs an RSC Data loader error once when SSR renders the default boundary", async () => {
let error = new Error("LOADER_ERROR");
let payload: RSCMatch["payload"] | undefined;
let response = await matchRSCServerRequest({
createTemporaryReferenceSet: () => ({}),
request: new Request("https://remix.run/"),
routes: [
{
id: "root",
path: "/",
Component: () => null,
loader() {
throw error;
},
},
],
generateResponse(match) {
payload = match.payload;
return new Response(null, { status: match.statusCode });
},
});
expect(response.status).toBe(500);

let decoded = Object.assign(Promise.resolve(payload!), {
formState: Promise.resolve(undefined),
});
let stream = await renderToReadableStream(
React.createElement(RSCStaticRouter, { getPayload: () => decoded }),
);
expect(await new Response(stream).text()).toContain(
"Unexpected Application Error!",
);
expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(error);
});

test("logs the underlying error for internal error responses", async () => {
await match(new Request("https://remix.run/does-not-exist"));
expect(consoleError).toHaveBeenCalledTimes(1);
expect(consoleError).toHaveBeenCalledWith(
new Error('No route matches URL "/does-not-exist"'),
);
});

test("does not log errors for aborted requests", async () => {
await match(
new Request("https://remix.run/aborted-resource", {
signal: abortController.signal,
}),
);
expect(consoleError).not.toHaveBeenCalled();
});
});
});

async function matchManifestRequest(
Expand Down
1 change: 1 addition & 0 deletions packages/react-router/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export const DataRouterNavigationContext =
DataRouterNavigationContext.displayName = "DataRouterNavigation";

export const RSCRouterContext = React.createContext<boolean>(false);
export const RSCErrorAlreadyReportedContext = React.createContext(false);

export function useIsRSCRouterContext(): boolean {
return React.useContext(RSCRouterContext);
Expand Down
12 changes: 8 additions & 4 deletions packages/react-router/lib/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
IsDataRouteContext,
LocationContext,
NavigationContext,
RSCErrorAlreadyReportedContext,
RSCRouterContext,
RouteContext,
RouteErrorContext,
Expand Down Expand Up @@ -975,6 +976,7 @@ export function useRoutesImpl(

function DefaultErrorComponent() {
let error = useRouteError();
let alreadyReported = React.useContext(RSCErrorAlreadyReportedContext);
let message = isRouteErrorResponse(error)
? `${error.status} ${error.statusText}`
: error instanceof Error
Expand All @@ -987,10 +989,12 @@ function DefaultErrorComponent() {

let devInfo = null;
if (ENABLE_DEV_WARNINGS) {
console.error(
"Error handled by React Router default ErrorBoundary:",
error,
);
if (!alreadyReported) {
console.error(
"Error handled by React Router default ErrorBoundary:",
error,
);
}

devInfo = (
<>
Expand Down
Loading