Unverified Commit ab1d9eeb authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

fix: handle server component replay error in error overlay (#71772)

### What

When there's a replay console error showed up, display it in error
overlay.

#### Server Component Page
<img width="480" alt="image"
src="https://github.com/user-attachments/assets/7af65809-1e0e-4aa0-bffb-bc95a376fb02">

#### Server Component Page with Client Components
<img width="480" alt="image"
src="https://github.com/user-attachments/assets/1f8bd507-3e0f-43f3-9240-07c4aec16ab4">

---------
Co-authored-by: 's avatarSebastian Markbage <sebastian@calyptus.eu>
parent 0dce6bb4
...@@ -13,13 +13,11 @@ export function patchConsoleError() { ...@@ -13,13 +13,11 @@ export function patchConsoleError() {
window.console.error = (...args: any[]) => { window.console.error = (...args: any[]) => {
let maybeError: unknown let maybeError: unknown
let isReplayed: boolean = false
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
const replayedError = matchReplayedError(...args) const replayedError = matchReplayedError(...args)
if (replayedError) { if (replayedError) {
maybeError = replayedError maybeError = replayedError
isReplayed = true
} else { } else {
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78 // See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
maybeError = args[1] maybeError = args[1]
...@@ -33,10 +31,7 @@ export function patchConsoleError() { ...@@ -33,10 +31,7 @@ export function patchConsoleError() {
handleClientError( handleClientError(
// replayed errors have their own complex format string that should be used, // replayed errors have their own complex format string that should be used,
// but if we pass the error directly, `handleClientError` will ignore it // but if we pass the error directly, `handleClientError` will ignore it
// maybeError,
// TODO: not passing an error here will make `handleClientError`
// create a new Error, so we'll lose the stack. we should make it smarter
isReplayed ? undefined : maybeError,
args args
) )
} }
......
...@@ -61,11 +61,22 @@ function ErrorDescription({ ...@@ -61,11 +61,22 @@ function ErrorDescription({
error: Error error: Error
hydrationWarning: string | null hydrationWarning: string | null
}) { }) {
const isUnhandledError = isUnhandledConsoleOrRejection(error) const isUnhandledOrReplayError = isUnhandledConsoleOrRejection(error)
// If there's hydration warning or console error, skip displaying the error name // If the error is:
// - hydration warning
// - captured console error or unhandled rejection
// skip displaying the error name
const title =
isUnhandledOrReplayError || hydrationWarning ? '' : error.name + ': '
// If it's replayed error, display the environment name
const environmentName =
'environmentName' in error ? error['environmentName'] : ''
const envPrefix = environmentName ? `[ ${environmentName} ] ` : ''
return ( return (
<> <>
{isUnhandledError || hydrationWarning ? '' : error.name + ': '} {envPrefix}
{title}
<HotlinkedText <HotlinkedText
text={hydrationWarning || error.message} text={hydrationWarning || error.message}
matcher={isNextjsLink} matcher={isNextjsLink}
......
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser' import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import type { OriginalStackFrameResponse } from '../../server/shared' import type { OriginalStackFrameResponse } from '../../server/shared'
import { isWebpackBundled, formatFrameSourceFile } from './webpack-module-path' import {
isWebpackInternalResource,
formatFrameSourceFile,
} from './webpack-module-path'
export interface OriginalStackFrame extends OriginalStackFrameResponse { export interface OriginalStackFrame extends OriginalStackFrameResponse {
error: boolean error: boolean
reason: string | null reason: string | null
...@@ -106,7 +109,7 @@ export function getOriginalStackFrames( ...@@ -106,7 +109,7 @@ export function getOriginalStackFrames(
export function getFrameSource(frame: StackFrame): string { export function getFrameSource(frame: StackFrame): string {
if (!frame.file) return '' if (!frame.file) return ''
const isWebpackFrame = isWebpackBundled(frame.file) const isWebpackFrame = isWebpackInternalResource(frame.file)
let str = '' let str = ''
// Skip URL parsing for webpack internal file paths. // Skip URL parsing for webpack internal file paths.
...@@ -137,11 +140,18 @@ export function getFrameSource(frame: StackFrame): string { ...@@ -137,11 +140,18 @@ export function getFrameSource(frame: StackFrame): string {
} }
} }
if (!isWebpackBundled(frame.file) && frame.lineNumber != null) { if (!isWebpackInternalResource(frame.file) && frame.lineNumber != null) {
if (frame.column != null) { // If the method name is replayed from server, e.g. Page [Server],
str += ` (${frame.lineNumber}:${frame.column})` // and it's formatted to empty string, recover it as <anonymous> to display it.
} else { if (!str && frame.methodName.endsWith(' [Server]')) {
str += ` (${frame.lineNumber})` str = '<anonymous>'
}
if (str) {
if (frame.column != null) {
str += ` (${frame.lineNumber}:${frame.column})`
} else {
str += ` (${frame.lineNumber})`
}
} }
} }
return str return str
......
import { formatFrameSourceFile, isWebpackBundled } from './webpack-module-path' import {
formatFrameSourceFile,
isWebpackInternalResource,
} from './webpack-module-path'
describe('webpack-module-path', () => { describe('webpack-module-path', () => {
describe('isWebpackBundled', () => { describe('isWebpackInternalResource', () => {
it('should return true for webpack-internal paths', () => { it('should return true for webpack-internal paths', () => {
expect(isWebpackBundled('webpack-internal:///./src/hello.tsx')).toBe(true)
expect( expect(
isWebpackBundled( isWebpackInternalResource('webpack-internal:///./src/hello.tsx')
).toBe(true)
expect(
isWebpackInternalResource(
'rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42' 'rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42'
) )
).toBe(true) ).toBe(true)
expect( expect(
isWebpackBundled( isWebpackInternalResource(
'rsc://React/Server/webpack:///(rsc)/./src/hello.tsx?42' 'rsc://React/Server/webpack:///(rsc)/./src/hello.tsx?42'
) )
).toBe(true) ).toBe(true)
expect( expect(
isWebpackBundled( isWebpackInternalResource(
'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42' 'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42'
) )
).toBe(true) ).toBe(true)
expect(isWebpackBundled('webpack://_N_E/./src/hello.tsx')).toBe(true) expect(
expect(isWebpackBundled('webpack://./src/hello.tsx')).toBe(true) isWebpackInternalResource(
expect(isWebpackBundled('webpack:///./src/hello.tsx')).toBe(true) 'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42dc'
)
).toBe(true)
expect(isWebpackInternalResource('webpack://_N_E/./src/hello.tsx')).toBe(
true
)
expect(isWebpackInternalResource('webpack://./src/hello.tsx')).toBe(true)
expect(isWebpackInternalResource('webpack:///./src/hello.tsx')).toBe(true)
}) })
it('should return false for non-webpack-internal paths', () => { it('should return false for non-webpack-internal paths', () => {
expect(isWebpackBundled('<anonymous>')).toBe(false) expect(isWebpackInternalResource('<anonymous>')).toBe(false)
expect(isWebpackBundled('file:///src/hello.tsx')).toBe(false) expect(isWebpackInternalResource('file:///src/hello.tsx')).toBe(false)
}) })
}) })
...@@ -50,6 +62,16 @@ describe('webpack-module-path', () => { ...@@ -50,6 +62,16 @@ describe('webpack-module-path', () => {
'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42' 'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42'
) )
).toBe('./src/hello.tsx') ).toBe('./src/hello.tsx')
expect(
formatFrameSourceFile(
'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42?0'
)
).toBe('./src/hello.tsx')
expect(
formatFrameSourceFile(
'rsc://React/Server/webpack:///(app-pages-browser)/./src/hello.tsx?42dc'
)
).toBe('./src/hello.tsx')
expect(formatFrameSourceFile('webpack://_N_E/./src/hello.tsx')).toBe( expect(formatFrameSourceFile('webpack://_N_E/./src/hello.tsx')).toBe(
'./src/hello.tsx' './src/hello.tsx'
) )
......
...@@ -2,10 +2,11 @@ const replacementRegExes = [ ...@@ -2,10 +2,11 @@ const replacementRegExes = [
/^(rsc:\/\/React\/[^/]+\/)/, /^(rsc:\/\/React\/[^/]+\/)/,
/^webpack-internal:\/\/\/(\([\w-]+\)\/)?/, /^webpack-internal:\/\/\/(\([\w-]+\)\/)?/,
/^(webpack:\/\/\/|webpack:\/\/(_N_E\/)?)(\([\w-]+\)\/)?/, /^(webpack:\/\/\/|webpack:\/\/(_N_E\/)?)(\([\w-]+\)\/)?/,
/\?\w+(\?\d+)?$/, // React replay error query param, .e.g. ?c69d?0, ?c69d
/\?\d+$/, // React's fakeFunctionIdx query param /\?\d+$/, // React's fakeFunctionIdx query param
] ]
export function isWebpackBundled(file: string) { export function isWebpackInternalResource(file: string) {
for (const regex of replacementRegExes) { for (const regex of replacementRegExes) {
if (regex.test(file)) return true if (regex.test(file)) return true
...@@ -19,6 +20,7 @@ export function isWebpackBundled(file: string) { ...@@ -19,6 +20,7 @@ export function isWebpackBundled(file: string) {
* Format the webpack internal id to original file path * Format the webpack internal id to original file path
* webpack-internal:///./src/hello.tsx => ./src/hello.tsx * webpack-internal:///./src/hello.tsx => ./src/hello.tsx
* rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42 => ./src/hello.tsx * rsc://React/Server/webpack-internal:///(rsc)/./src/hello.tsx?42 => ./src/hello.tsx
* rsc://React/Server/webpack:///app/indirection.tsx?14cb?0 => app/indirection.tsx
* webpack://_N_E/./src/hello.tsx => ./src/hello.tsx * webpack://_N_E/./src/hello.tsx => ./src/hello.tsx
* webpack://./src/hello.tsx => ./src/hello.tsx * webpack://./src/hello.tsx => ./src/hello.tsx
* webpack:///./src/hello.tsx => ./src/hello.tsx * webpack:///./src/hello.tsx => ./src/hello.tsx
......
...@@ -33,7 +33,7 @@ describe('dynamic = "error" in devmode', () => { ...@@ -33,7 +33,7 @@ describe('dynamic = "error" in devmode', () => {
await session.assertHasRedbox() await session.assertHasRedbox()
console.log(await session.getRedboxDescription()) console.log(await session.getRedboxDescription())
expect(await session.getRedboxDescription()).toMatchInlineSnapshot( expect(await session.getRedboxDescription()).toMatchInlineSnapshot(
`"Error: Route /server with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering"` `"[ Server ] Error: Route /server with \`dynamic = "error"\` couldn't be rendered statically because it used \`cookies\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering"`
) )
await cleanup() await cleanup()
......
...@@ -196,12 +196,12 @@ describe('app-dir - capture-console-error', () => { ...@@ -196,12 +196,12 @@ describe('app-dir - capture-console-error', () => {
{ {
"callStacks": "", "callStacks": "",
"count": 1, "count": 1,
"description": "[ Server ] Error: boom", "description": "[ Server ] Error: boom",
"source": "app/rsc/page.js (2:11) @ Page "source": "app/rsc/page.js (2:17) @ Page
1 | export default function Page() { 1 | export default function Page() {
> 2 | console.error(new Error('boom')) > 2 | console.error(new Error('boom'))
| ^ | ^
3 | return <p>rsc</p> 3 | return <p>rsc</p>
4 | } 4 | }
5 |", 5 |",
...@@ -212,12 +212,12 @@ describe('app-dir - capture-console-error', () => { ...@@ -212,12 +212,12 @@ describe('app-dir - capture-console-error', () => {
{ {
"callStacks": "", "callStacks": "",
"count": 1, "count": 1,
"description": "[ Server ] Error: boom", "description": "[ Server ] Error: boom",
"source": "app/rsc/page.js (2:11) @ error "source": "app/rsc/page.js (2:17) @ Page
1 | export default function Page() { 1 | export default function Page() {
> 2 | console.error(new Error('boom')) > 2 | console.error(new Error('boom'))
| ^ | ^
3 | return <p>rsc</p> 3 | return <p>rsc</p>
4 | } 4 | }
5 |", 5 |",
......
export default async function Page() {
await new Promise((r) => setTimeout(r, 200))
return <p>Page</p>
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { import {
assertHasRedbox,
getRedboxCallStack,
getRedboxDescription, getRedboxDescription,
hasErrorToast, hasErrorToast,
retry, retry,
...@@ -20,7 +22,7 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -20,7 +22,7 @@ describe('Dynamic IO Dev Errors', () => {
await waitForAndOpenRuntimeError(browser) await waitForAndOpenRuntimeError(browser)
expect(await getRedboxDescription(browser)).toMatchInlineSnapshot( expect(await getRedboxDescription(browser)).toMatchInlineSnapshot(
`"[ Server ] Error: Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random"` `"[ Server ] Error: Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random"`
) )
}) })
}) })
...@@ -38,8 +40,35 @@ describe('Dynamic IO Dev Errors', () => { ...@@ -38,8 +40,35 @@ describe('Dynamic IO Dev Errors', () => {
await waitForAndOpenRuntimeError(browser) await waitForAndOpenRuntimeError(browser)
expect(await getRedboxDescription(browser)).toMatchInlineSnapshot( expect(await getRedboxDescription(browser)).toMatchInlineSnapshot(
`"[ Server ] Error: Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random"` `"[ Server ] Error: Route "/error" used \`Math.random()\` outside of \`"use cache"\` and without explicitly calling \`await connection()\` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-random"`
) )
}) })
}) })
it('should display error when component accessed data without suspense boundary', async () => {
const browser = await next.browser('/no-accessed-data')
await retry(async () => {
expect(await hasErrorToast(browser)).toBe(true)
await waitForAndOpenRuntimeError(browser)
await assertHasRedbox(browser)
})
const description = await getRedboxDescription(browser)
const stack = await getRedboxCallStack(browser)
const result = {
description,
stack,
}
expect(result).toMatchInlineSnapshot(`
{
"description": "[ Server ] Error: In Route "/no-accessed-data" this component accessed data without a Suspense boundary above it to provide a fallback UI. See more info: https://nextjs.org/docs/messages/next-prerender-data",
"stack": "Page [Server]
<anonymous> (2:1)
Root [Server]
<anonymous> (2:1)",
}
`)
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment