Unverified Commit 22eff625 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

capture console.error into error overlay (#71424)

parent 0518f69e
import { isNextRouterError } from '../is-next-router-error'
import { handleClientError } from '../react-dev-overlay/internal/helpers/use-error-handler'
const originConsoleError = window.console.error
// Patch console.error to collect information about hydration errors
export function patchConsoleError() {
// Ensure it's only patched once
......@@ -8,18 +10,13 @@ export function patchConsoleError() {
return
}
const originConsoleError = window.console.error
window.console.error = (...args) => {
window.console.error = (...args: any[]) => {
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
if (!isNextRouterError(error)) {
if (process.env.NODE_ENV !== 'production') {
const { storeHydrationErrorStateFromConsoleArgs } =
require('../react-dev-overlay/internal/helpers/hydration-error-info') as typeof import('../react-dev-overlay/internal/helpers/hydration-error-info')
storeHydrationErrorStateFromConsoleArgs(...args)
handleClientError(error)
handleClientError(error, args)
}
originConsoleError.apply(window.console, args)
......
......@@ -566,7 +566,7 @@ export default function HotReload({
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack!),
frames: parseStack(error.stack),
componentStackFrames:
typeof componentStackTrace === 'string'
? parseComponentStack(componentStackTrace)
......
......@@ -31,6 +31,7 @@ import {
} from '../helpers/hydration-error-info'
import { NodejsInspectorCopyButton } from '../components/nodejs-inspector'
import { CopyButton } from '../components/copy-button'
import { ConsoleError } from '../helpers/console-error'
export type SupportedErrorEvent = {
id: number
......@@ -53,6 +54,26 @@ function isNextjsLink(text: string): boolean {
return text.startsWith('https://nextjs.org')
}
function ErrorDescription({
error,
hydrationWarning,
}: {
error: Error
hydrationWarning: string | null
}) {
const isFromConsoleError = error instanceof ConsoleError
// If there's hydration warning or console error, skip displaying the error name
return (
<>
{isFromConsoleError || hydrationWarning ? '' : error.name + ': '}
<HotlinkedText
text={hydrationWarning || error.message}
matcher={isNextjsLink}
/>
</>
)
}
function getErrorSignature(ev: SupportedErrorEvent): string {
const { event } = ev
switch (event.type) {
......@@ -236,6 +257,7 @@ export function Errors({
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(error) || ''
)
const isFromConsoleError = error instanceof ConsoleError
const errorDetails: HydrationErrorState = (error as any).details || {}
const notes = errorDetails.notes || ''
......@@ -284,7 +306,11 @@ export function Errors({
id="nextjs__container_errors_label"
className="nextjs__container_errors_label"
>
{isServerError ? 'Server Error' : 'Unhandled Runtime Error'}
{isServerError
? 'Server Error'
: isFromConsoleError
? 'Console Error'
: 'Unhandled Runtime Error'}
</h1>
<span>
<CopyButton
......@@ -304,11 +330,9 @@ export function Errors({
id="nextjs__container_errors_desc"
className="nextjs__container_errors_desc"
>
{/* If there's hydration warning, skip displaying the error name */}
{hydrationWarning ? '' : error.name + ': '}
<HotlinkedText
text={hydrationWarning || error.message}
matcher={isNextjsLink}
<ErrorDescription
error={error}
hydrationWarning={hydrationWarning}
/>
</p>
{notes ? (
......
export class ConsoleError extends Error {
constructor(message: string) {
super(message)
this.name = 'ConsoleError'
}
}
......@@ -7,7 +7,8 @@ import {
const regexNextStatic = /\/_next(\/static\/.+)/
export function parseStack(stack: string): StackFrame[] {
export function parseStack(stack: string | undefined): StackFrame[] {
if (!stack) return []
const messageAndStack = stack.replace(/^Error: /, '')
if (isReactHydrationErrorStack(messageAndStack)) {
const { stack: parsedStack } = getHydrationErrorStackInfo(messageAndStack)
......
......@@ -2,29 +2,41 @@ import { useEffect } from 'react'
import { isHydrationError } from '../../../is-hydration-error'
import { attachHydrationErrorState } from './attach-hydration-error-state'
import { isNextRouterError } from '../../../is-next-router-error'
import { storeHydrationErrorStateFromConsoleArgs } from './hydration-error-info'
import { formatConsoleArgs } from '../../../../lib/console'
import isError from '../../../../../lib/is-error'
import { ConsoleError } from './console-error'
export type ErrorHandler = (error: Error) => void
let hasHydrationError = false
const errorQueue: Array<Error> = []
const errorHandlers: Array<ErrorHandler> = []
const rejectionQueue: Array<Error> = []
const rejectionHandlers: Array<ErrorHandler> = []
export function handleClientError(error: unknown) {
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
export function handleClientError(
originError: unknown,
consoleErrorArgs: any[]
) {
let error: Error
if (!originError || !isError(originError)) {
// If it's not an error, format the args into an error
const formattedErrorMessage = formatConsoleArgs(consoleErrorArgs)
error = new ConsoleError(formattedErrorMessage)
} else {
error = originError
}
storeHydrationErrorStateFromConsoleArgs(...consoleErrorArgs)
attachHydrationErrorState(error)
// Only queue one hydration every time
// TODO: change all to push error into errorQueue,
// currently there's a async api error is always erroring while hydration error showing up.
// Move hydration error to the front of the queue to unblock.
if (isHydrationError(error)) {
if (!hasHydrationError) {
errorQueue.push(error)
}
hasHydrationError = true
errorQueue.unshift(error)
} else {
errorQueue.push(error)
}
for (const handler of errorHandlers) {
handler(error)
......@@ -69,7 +81,7 @@ export function handleGlobalErrors() {
event.preventDefault()
return false
}
handleClientError(event.error)
handleClientError(event.error, [])
}
)
......
......@@ -44,7 +44,7 @@ function handleError(error: unknown) {
Bus.emit({
type: ACTION_UNHANDLED_ERROR,
reason: error,
frames: parseStack(error.stack!),
frames: parseStack(error.stack),
componentStackFrames,
})
}
......
function formatObject(arg: unknown, depth: number) {
switch (typeof arg) {
case 'object':
if (arg === null) {
return 'null'
} else if (Array.isArray(arg)) {
let result = '['
if (depth < 1) {
for (let i = 0; i < arg.length; i++) {
if (result !== '[') {
result += ','
}
if (Object.prototype.hasOwnProperty.call(arg, i)) {
result += formatObject(arg[i], depth + 1)
}
}
} else {
result += arg.length > 0 ? '...' : ''
}
result += ']'
return result
} else if (arg instanceof Error) {
return arg + ''
} else {
const keys = Object.keys(arg)
let result = '{'
if (depth < 1) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const desc = Object.getOwnPropertyDescriptor(arg, 'key')
if (desc && !desc.get && !desc.set) {
const jsonKey = JSON.stringify(key)
if (jsonKey !== '"' + key + '"') {
result += jsonKey + ': '
} else {
result += key + ': '
}
result += formatObject(desc.value, depth + 1)
}
}
} else {
result += keys.length > 0 ? '...' : ''
}
result += '}'
return result
}
case 'string':
return JSON.stringify(arg)
default:
return String(arg)
}
}
export function formatConsoleArgs(args: unknown[]): string {
let message: string
let idx: number
if (typeof args[0] === 'string') {
message = args[0]
idx = 1
} else {
message = ''
idx = 0
}
let result = ''
let startQuote = false
for (let i = 0; i < message.length; ++i) {
const char = message[i]
if (char !== '%' || i === message.length - 1 || idx >= args.length) {
result += char
continue
}
const code = message[++i]
switch (code) {
case 'c': {
// TODO: We should colorize with HTML instead of turning into a string.
// Ignore for now.
result = startQuote ? `${result}]` : `[${result}`
startQuote = !startQuote
idx++
break
}
case 'O':
case 'o': {
result += formatObject(args[idx++], 0)
break
}
case 'd':
case 'i': {
result += parseInt(args[idx++] as any, 10)
break
}
case 'f': {
result += parseFloat(args[idx++] as any)
break
}
case 's': {
result += String(args[idx++])
break
}
default:
result += '%' + code
}
}
for (; idx < args.length; idx++) {
result += (idx > 0 ? ' ' : '') + formatObject(args[idx], 0)
}
return result
}
......@@ -3,7 +3,7 @@ import { sandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { outdent } from 'outdent'
import { getRedboxTotalErrorCount } from 'next-test-utils'
import { getRedboxTotalErrorCount, retry } from 'next-test-utils'
// https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference
......@@ -355,8 +355,7 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
// FIXME: Should be 2
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
expect(await getRedboxTotalErrorCount(browser)).toBe(2)
// FIXME: Should also have "text nodes cannot be a child of tr"
expect(await session.getRedboxDescription()).toEqual(outdent`
......@@ -385,7 +384,7 @@ describe('Error overlay for hydration errors in App router', () => {
})
it('should show correct hydration error when server renders an extra whitespace in an invalid place', async () => {
const { cleanup, session } = await sandbox(
const { cleanup, session, browser } = await sandbox(
next,
new Map([
[
......@@ -405,22 +404,40 @@ describe('Error overlay for hydration errors in App router', () => {
])
)
// FIXME: Should have getRedboxDescription() "text nodes cannot be a child of tr"
await expect(session.hasErrorToast()).resolves.toBe(false)
await session.waitForAndOpenRuntimeError()
// await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
await retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
})
// expect(await session.hasRedbox()).toBe(false)
// expect(await getRedboxTotalErrorCount(browser)).toBe(0)
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"In HTML, whitespace text nodes cannot be a child of <table>. Make sure you don't have any extra whitespace between tags on each line of your source code.
This will cause a hydration error.
// expect(await session.getRedboxDescription()).toEqual(outdent`
// Something
// `)
...
<RenderFromTemplateContext>
<ScrollAndFocusHandler segmentPath={[...]}>
<InnerScrollAndFocusHandler segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary hasLoading={false} loading={undefined} loadingStyles={undefined} loadingScripts={undefined}>
<NotFoundBoundary notFound={[...]} notFoundStyles={[...]}>
<NotFoundErrorBoundary pathname="/" notFound={[...]} notFoundStyles={[...]} asNotFound={undefined} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter parallelRouterKey="children" url="/" tree={[...]} childNodes={Map} ...>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}>
> <table>
> {" "}
...
...
"
`)
// FIXME: fix the `pseudoHtml` should be extracted from the description
// const pseudoHtml = await session.getRedboxComponentStack()
// expect(pseudoHtml).toEqual(outdent`
// Something
// `)
// expect(pseudoHtml).toMatchInlineSnapshot(``)
await cleanup()
})
......@@ -542,7 +559,7 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
expect(await getRedboxTotalErrorCount(browser)).toBe(2)
const description = await session.getRedboxDescription()
expect(description).toContain(
......@@ -602,7 +619,7 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
expect(await getRedboxTotalErrorCount(browser)).toBe(2)
const description = await session.getRedboxDescription()
expect(description).toContain(
......@@ -642,7 +659,7 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
expect(await getRedboxTotalErrorCount(browser)).toBe(2)
const description = await session.getRedboxDescription()
expect(description).toEqual(outdent`
......@@ -697,7 +714,7 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
expect(await getRedboxTotalErrorCount(browser)).toBe(2)
const description = await session.getRedboxDescription()
expect(description).toContain(
......@@ -771,7 +788,10 @@ describe('Error overlay for hydration errors in App router', () => {
await session.waitForAndOpenRuntimeError()
await session.assertHasRedbox()
expect(await getRedboxTotalErrorCount(browser)).toBe(1)
retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(4)
})
const description = await session.getRedboxDescription()
expect(description).toEqual(outdent`
......
'use client'
export default function Page() {
return (
<button
onClick={() => {
console.error('trigger an console <%s>', 'error')
}}
>
click to error
</button>
)
}
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
console.error(new Error('boom'))
return <p>rsc</p>
}
'use client'
export default function Page() {
console.error(
'ssr console error:' + (typeof window === 'undefined' ? 'server' : 'client')
)
if (typeof window === 'undefined') {
}
return <p>ssr</p>
}
import { nextTestSetup } from 'e2e-utils'
import {
assertHasRedbox,
getRedboxCallStack,
getRedboxDescription,
getRedboxSource,
getRedboxTotalErrorCount,
waitForAndOpenRuntimeError,
} from 'next-test-utils'
async function getRedboxResult(browser: any) {
const description = await getRedboxDescription(browser)
const callStacks = await getRedboxCallStack(browser)
const count = await getRedboxTotalErrorCount(browser)
const source = await getRedboxSource(browser)
const result = {
count,
source,
description,
callStacks,
}
return result
}
describe('app-dir - capture-console-error', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should capture browser console error and format the error message', async () => {
const browser = await next.browser('/browser')
await browser.elementByCss('button').click()
await waitForAndOpenRuntimeError(browser)
await assertHasRedbox(browser)
const result = await getRedboxResult(browser)
if (process.env.TURBOPACK) {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 1,
"description": "trigger an console <error>",
"source": "app/browser/page.js (7:17) @ onClick
5 | <button
6 | onClick={() => {
> 7 | console.error('trigger an console <%s>', 'error')
| ^
8 | }}
9 | >
10 | click to error",
}
`)
} else {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 1,
"description": "trigger an console <error>",
"source": "app/browser/page.js (7:17) @ error
5 | <button
6 | onClick={() => {
> 7 | console.error('trigger an console <%s>', 'error')
| ^
8 | }}
9 | >
10 | click to error",
}
`)
}
})
it('should capture server replay console error', async () => {
const browser = await next.browser('/ssr')
await waitForAndOpenRuntimeError(browser)
await assertHasRedbox(browser)
const result = await getRedboxResult(browser)
if (process.env.TURBOPACK) {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 2,
"description": "ssr console error:client",
"source": "app/ssr/page.js (4:11) @ Page
2 |
3 | export default function Page() {
> 4 | console.error(
| ^
5 | 'ssr console error:' + (typeof window === 'undefined' ? 'server' : 'client')
6 | )
7 | if (typeof window === 'undefined') {",
}
`)
} else {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 2,
"description": "ssr console error:client",
"source": "app/ssr/page.js (4:11) @ error
2 |
3 | export default function Page() {
> 4 | console.error(
| ^
5 | 'ssr console error:' + (typeof window === 'undefined' ? 'server' : 'client')
6 | )
7 | if (typeof window === 'undefined') {",
}
`)
}
})
it('should be able to capture rsc logged error', async () => {
const browser = await next.browser('/rsc')
await waitForAndOpenRuntimeError(browser)
await assertHasRedbox(browser)
const result = await getRedboxResult(browser)
if (process.env.TURBOPACK) {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 1,
"description": "[ Server ] Error: boom",
"source": "app/rsc/page.js (2:11) @ Page
1 | export default function Page() {
> 2 | console.error(new Error('boom'))
| ^
3 | return <p>rsc</p>
4 | }
5 |",
}
`)
} else {
expect(result).toMatchInlineSnapshot(`
{
"callStacks": "",
"count": 1,
"description": "[ Server ] Error: boom",
"source": "app/rsc/page.js (2:11) @ error
1 | export default function Page() {
> 2 | console.error(new Error('boom'))
| ^
3 | return <p>rsc</p>
4 | }
5 |",
}
`)
}
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
......@@ -103,6 +103,7 @@ describe('next-image-proxy', () => {
const expected = JSON.stringify({ fulfilledCount: 4, failCount: 0 })
await check(() => JSON.stringify({ fulfilledCount, failCount }), expected)
await browser.close()
})
it('should work with connection upgrade by removing it via filterReqHeaders()', async () => {
......
......@@ -916,10 +916,8 @@ export async function getRedboxHeader(browser: BrowserInterface) {
}
export async function getRedboxTotalErrorCount(browser: BrowserInterface) {
return parseInt(
(await getRedboxHeader(browser)).match(/\d+ of (\d+) error/)?.[1],
10
)
const header = (await getRedboxHeader(browser)) || ''
return parseInt(header.match(/\d+ of (\d+) error/)?.[1], 10)
}
export async function getRedboxSource(browser: BrowserInterface) {
......
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