Unverified Commit 871ca31e authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[app] Send errors not handled by explicit error boundaries through `reportError` (#76101)

parent 0dc87f71
......@@ -244,11 +244,11 @@ function Root({ children }: React.PropsWithChildren<{}>) {
return children
}
const reactRootOptions = {
const reactRootOptions: ReactDOMClient.RootOptions = {
onRecoverableError,
onCaughtError,
onUncaughtError,
} satisfies ReactDOMClient.RootOptions
}
export function hydrate() {
const reactEl = (
......
......@@ -3,7 +3,7 @@ import { isNextRouterError } from '../is-next-router-error'
import { handleClientError } from '../errors/use-error-handler'
import { parseConsoleArgs } from '../../lib/console'
export const originConsoleError = window.console.error
export const originConsoleError = globalThis.console.error
// Patch console.error to collect information about hydration errors
export function patchConsoleError() {
......
// This file is only used in app router due to the specific error state handling.
import type { HydrationOptions } from 'react-dom/client'
import type { ErrorInfo } from 'react'
import { getReactStitchedError } from '../components/errors/stitched-error'
import { handleClientError } from '../components/errors/use-error-handler'
import { isNextRouterError } from '../components/is-next-router-error'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { reportGlobalError } from './report-global-error'
import { originConsoleError } from '../components/globals/intercept-console-error'
import { AppDevOverlayErrorBoundary } from '../components/react-dev-overlay/app/app-dev-overlay-error-boundary'
import {
ErrorBoundaryHandler,
GlobalError as DefaultErrorBoundary,
} from '../components/error-boundary'
export function onCaughtError(
err: unknown,
errorInfo: ErrorInfo & { errorBoundary?: React.Component }
) {
const errorBoundaryComponent = errorInfo.errorBoundary?.constructor
const isImplicitErrorBoundary =
(process.env.NODE_ENV !== 'production' &&
errorBoundaryComponent === AppDevOverlayErrorBoundary) ||
(errorBoundaryComponent === ErrorBoundaryHandler &&
(errorInfo.errorBoundary! as InstanceType<typeof ErrorBoundaryHandler>)
.props.errorComponent === DefaultErrorBoundary)
if (isImplicitErrorBoundary) {
// We don't consider errors caught unless they're caught by an explicit error
// boundary. The built-in ones are considered implicit.
// This mimics how the same app would behave without Next.js.
return onUncaughtError(err, errorInfo)
}
export const onCaughtError: HydrationOptions['onCaughtError'] = (
err,
errorInfo
) => {
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err) || isNextRouterError(err)) return
if (process.env.NODE_ENV !== 'production') {
const errorBoundaryComponent = errorInfo?.errorBoundary?.constructor
const errorBoundaryName =
// read react component displayName
(errorBoundaryComponent as any)?.displayName ||
......@@ -57,26 +76,11 @@ export const onCaughtError: HydrationOptions['onCaughtError'] = (
}
}
export const onUncaughtError: HydrationOptions['onUncaughtError'] = (
err,
errorInfo
) => {
export function onUncaughtError(err: unknown, errorInfo: React.ErrorInfo) {
// Skip certain custom errors which are not expected to be reported on client
if (isBailoutToCSRError(err) || isNextRouterError(err)) return
if (process.env.NODE_ENV !== 'production') {
const componentThatErroredFrame = errorInfo?.componentStack?.split('\n')[1]
// Match chrome or safari stack trace
const matches =
componentThatErroredFrame?.match(/\s+at (\w+)\s+|(\w+)@/) ?? []
const componentThatErroredName = matches[1] || matches[2] || 'Unknown'
// Create error location with errored component and error boundary, to match the behavior of default React onCaughtError handler.
const errorLocation = componentThatErroredName
? `The above error occurred in the <${componentThatErroredName}> component.`
: `The above error occurred in one of your components.`
const stitchedError = getReactStitchedError(err)
// TODO: change to passing down errorInfo later
// In development mode, pass along the component stack to the error
......@@ -84,8 +88,7 @@ export const onUncaughtError: HydrationOptions['onUncaughtError'] = (
;(stitchedError as any)._componentStack = errorInfo.componentStack
}
// Log and report the error with location but without modifying the error stack
originConsoleError('%o\n\n%s', err, errorLocation)
// TODO: Add an adendum to the overlay telling people about custom error boundaries.
reportGlobalError(stitchedError)
} else {
reportGlobalError(err)
......
......@@ -4,5 +4,6 @@ export const reportGlobalError =
// emulating an uncaught JavaScript error.
reportError
: (error: unknown) => {
window.console.error(error)
// TODO: Dispatch error event
globalThis.console.error(error)
}
/* eslint-env jest */
import {
assertHasRedbox,
assertNoRedbox,
fetchViaHTTP,
getRedboxSource,
getRedboxHeader,
waitFor,
check,
} from 'next-test-utils'
import { assertNoRedbox, fetchViaHTTP, waitFor, check } from 'next-test-utils'
import webdriver, { BrowserInterface } from 'next-webdriver'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
......@@ -16,7 +8,7 @@ import { nextTestSetup } from 'e2e-utils'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
describe('Client Navigation', () => {
const { next } = nextTestSetup({
const { isTurbopack, next } = nextTestSetup({
files: path.join(__dirname, 'fixture'),
env: {
TEST_STRICT_NEXT_HEAD: String(true),
......@@ -281,10 +273,16 @@ describe('Client Navigation', () => {
},
})
await browser.elementByCss('#empty-props').click()
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toMatch(
/should resolve to an object\. But found "null" instead\./
)
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: "EmptyInitialPropsPage.getInitialProps()" should resolve to an object. But found "null" instead.",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": null,
"stack": [],
}
`)
expect(pageErrors).toEqual([
expect.objectContaining({
message:
......@@ -1393,11 +1391,20 @@ describe('Client Navigation', () => {
})
},
})
await assertHasRedbox(browser)
const text = await getRedboxSource(browser)
expect(text).toMatch(/An Expected error occurred/)
expect(text).toMatch(/pages[\\/]error-inside-browser-page\.js \(5:13\)/)
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: An Expected error occurred",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "pages/error-inside-browser-page.js (5:13) @ ErrorInRenderPage.render
> 5 | throw new Error('An Expected error occurred')
| ^",
"stack": [
"ErrorInRenderPage.render pages/error-inside-browser-page.js (5:13)",
],
}
`)
expect(pageErrors).toEqual(
isReact18
? [
......@@ -1437,10 +1444,42 @@ describe('Client Navigation', () => {
},
}
)
await assertHasRedbox(browser)
const text = await getRedboxSource(browser)
expect(text).toMatch(/An Expected error occurred/)
expect(text).toMatch(/error-in-the-browser-global-scope\.js \(2:9\)/)
if (isTurbopack) {
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: An Expected error occurred",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "pages/error-in-the-browser-global-scope.js (2:9) @ [project]/pages/error-in-the-browser-global-scope.js [client] (ecmascript)
> 2 | throw new Error('An Expected error occurred')
| ^",
"stack": [
"[project]/pages/error-in-the-browser-global-scope.js [client] (ecmascript) pages/error-in-the-browser-global-scope.js (2:9)",
],
}
`)
} else {
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: An Expected error occurred",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "pages/error-in-the-browser-global-scope.js (2:9) @ eval
> 2 | throw new Error('An Expected error occurred')
| ^",
"stack": [
"eval pages/error-in-the-browser-global-scope.js (2:9)",
"<FIXME-file-protocol>",
"<FIXME-file-protocol>",
"<FIXME-file-protocol>",
"<FIXME-file-protocol>",
],
}
`)
}
expect(pageErrors).toEqual([
expect.objectContaining({ message: 'An Expected error occurred' }),
])
......
import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox, getRedboxHeader, retry } from 'next-test-utils'
import { retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
describe('app-dir - errors', () => {
......@@ -174,8 +174,20 @@ describe('app-dir - errors', () => {
await browser.elementByCss('#error-trigger-button').click()
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toMatch(/this is a test/)
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: this is a test",
"environmentLabel": null,
"label": "Unhandled Runtime Error",
"source": "app/global-error-boundary/client/page.js (8:11) @ Page
> 8 | throw new Error('this is a test')
| ^",
"stack": [
"Page app/global-error-boundary/client/page.js (8:11)",
],
}
`)
} else {
expect(
await browser.waitForElementByCss('body').elementByCss('h2').text()
......@@ -184,8 +196,11 @@ describe('app-dir - errors', () => {
)
}
// FIXME(veil): Should contain thrown error.
expect(pageErrors).toEqual([])
expect(pageErrors).toEqual([
expect.objectContaining({
message: 'this is a test',
}),
])
})
it('should display error digest for error in server component with default error boundary', async () => {
......@@ -199,8 +214,20 @@ describe('app-dir - errors', () => {
})
if (isNextDev) {
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toMatch(/custom server error/)
await expect(browser).toDisplayRedbox(`
{
"count": 1,
"description": "Error: custom server error",
"environmentLabel": "Server",
"label": "Unhandled Runtime Error",
"source": "app/global-error-boundary/server/page.js (2:9) @ Page
> 2 | throw Error('custom server error')
| ^",
"stack": [
"Page app/global-error-boundary/server/page.js (2:9)",
],
}
`)
} else {
expect(
await browser.waitForElementByCss('body').elementByCss('h2').text()
......@@ -212,8 +239,15 @@ describe('app-dir - errors', () => {
).toMatch(/Digest: \w+/)
}
// FIXME(veil): Should contain thrown error.
expect(pageErrors).toEqual([])
expect(pageErrors).toEqual([
expect.objectContaining({
message: isNextDev
? 'custom server error'
: 'An error occurred in the Server Components render. ' +
'The specific message is omitted in production builds to avoid leaking sensitive details. ' +
'A digest property is included on this error instance which may provide additional details about the nature of the error.',
}),
])
})
// production tests
......@@ -244,13 +278,17 @@ describe('app-dir - errors', () => {
})
it('should hydrate empty shell to handle server-side rendering errors', async () => {
const browser = await next.browser('/ssr-error-client-component')
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toInclude('Error during SSR')
const pageErrors: unknown[] = []
await next.browser('/ssr-error-client-component', {
beforePageLoad: (page) => {
page.on('pageerror', (error: unknown) => {
pageErrors.push(error)
})
},
})
expect(pageErrors).toEqual([
expect.objectContaining({ message: 'Error during SSR' }),
])
})
it('should log the original RSC error trace in production', async () => {
......
......@@ -30,6 +30,7 @@ declare global {
* Unintented content in the snapshot should be reported to the Next.js DX team.
* `<FIXME-internal-frame>` in the snapshot would be unintended.
* `<FIXME-project-root>` in the snapshot would be unintended.
* `<FIXME-file-protocol>` in the snapshot would be unintended.
* Any node_modules in the snapshot would be unintended.
* Differences in the snapshot between Turbopack and Webpack would be unintended.
*
......@@ -48,6 +49,7 @@ declare global {
* Unintented content in the snapshot should be reported to the Next.js DX team.
* `<FIXME-internal-frame>` in the snapshot would be unintended.
* `<FIXME-project-root>` in the snapshot would be unintended.
* `<FIXME-file-protocol>` in the snapshot would be unintended.
* Any node_modules in the snapshot would be unintended.
* Differences in the snapshot between Turbopack and Webpack would be unintended.
*
......
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