Unverified Commit ea541987 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

fix: handling of falsey values in error boundaries (#93134)

our error boundaries had a bunch of logic that set `state.error = error`
and then checked `if (state.error)`, which only works correctly if
thrown value is truthy. it breaks if something does e.g. `throw
undefined`. in this case, we would incorrectly think that no error
occurred and render children again (instead of a fallback), which can
then lead to an infinite loop if the children throw again.

the fix is to wrap the thrown value, so `state.error` is either `null`
(initial/reset) or `{ thrownValue: ... }` if something errored. i
initially considered using a separate `state.hasError` boolean, but
that's a bit annoying to type, and really we want to model this as a
discriminated union, so using a pseudo-Optional thing is nicer.
parent 70d98765
...@@ -30,7 +30,7 @@ type CatchErrorProps<P extends UserProps> = { ...@@ -30,7 +30,7 @@ type CatchErrorProps<P extends UserProps> = {
} }
type CatchErrorState = { type CatchErrorState = {
error: Error | null error: null | { thrownValue: unknown }
previousPathname: string | null previousPathname: string | null
} }
...@@ -38,7 +38,7 @@ type CatchErrorState = { ...@@ -38,7 +38,7 @@ type CatchErrorState = {
// TODO: Extend it instead of forking to easily sync the behavior? // TODO: Extend it instead of forking to easily sync the behavior?
class CatchError<P extends UserProps> extends React.Component< class CatchError<P extends UserProps> extends React.Component<
CatchErrorProps<P>, CatchErrorProps<P>,
{ error: Error | null; previousPathname: string | null } CatchErrorState
> { > {
declare context: AppRouterInstance | null declare context: AppRouterInstance | null
static contextType = AppRouterContext static contextType = AppRouterContext
...@@ -54,14 +54,16 @@ class CatchError<P extends UserProps> extends React.Component< ...@@ -54,14 +54,16 @@ class CatchError<P extends UserProps> extends React.Component<
} }
} }
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(
if (isNextRouterError(error)) { thrownValue: unknown
): Partial<CatchErrorState> {
if (isNextRouterError(thrownValue)) {
// Re-throw if an expected internal Next.js router error occurs // Re-throw if an expected internal Next.js router error occurs
// this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment) // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
throw error throw thrownValue
} }
return { error } return { error: { thrownValue } }
} }
static getDerivedStateFromProps( static getDerivedStateFromProps(
...@@ -75,7 +77,7 @@ class CatchError<P extends UserProps> extends React.Component< ...@@ -75,7 +77,7 @@ class CatchError<P extends UserProps> extends React.Component<
// the error boundary and instead should fallback // the error boundary and instead should fallback
// to a hard navigation to attempt recovering // to a hard navigation to attempt recovering
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
if (error && handleHardNavError(error)) { if (error && handleHardNavError(error.thrownValue)) {
// clear error so we don't render anything // clear error so we don't render anything
return { return {
error: null, error: null,
...@@ -124,13 +126,15 @@ class CatchError<P extends UserProps> extends React.Component< ...@@ -124,13 +126,15 @@ class CatchError<P extends UserProps> extends React.Component<
//When it's bot request, segment level error boundary will keep rendering the children, //When it's bot request, segment level error boundary will keep rendering the children,
// the final error will be caught by the root error boundary and determine wether need to apply graceful degrade. // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.
if (this.state.error && !isBotUserAgent) { if (this.state.error && !isBotUserAgent) {
handleISRError({ error: this.state.error }) const thrownValue = this.state.error.thrownValue
handleISRError({ error: thrownValue })
return ( return (
<this.props.fallback <this.props.fallback
props={this.props.props} props={this.props.props}
errorInfo={{ errorInfo={{
error: this.state.error, // TODO(NAR-804): Docs say this is an Error object, but we don't guarantee that
error: thrownValue,
reset: this.reset, reset: this.reset,
unstable_retry: this.unstable_retry, unstable_retry: this.unstable_retry,
}} }}
......
...@@ -15,7 +15,7 @@ const isBotUserAgent = ...@@ -15,7 +15,7 @@ const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent) typeof window !== 'undefined' && isBot(window.navigator.userAgent)
export type ErrorInfo = { export type ErrorInfo = {
error: Error error: unknown
reset: () => void reset: () => void
unstable_retry: () => void unstable_retry: () => void
} }
...@@ -35,7 +35,7 @@ interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps { ...@@ -35,7 +35,7 @@ interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {
} }
interface ErrorBoundaryHandlerState { interface ErrorBoundaryHandlerState {
error: Error | null error: null | { thrownValue: unknown }
previousPathname: string | null previousPathname: string | null
} }
...@@ -54,14 +54,16 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -54,14 +54,16 @@ export class ErrorBoundaryHandler extends React.Component<
} }
} }
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(
if (isNextRouterError(error)) { thrownValue: unknown
): Partial<ErrorBoundaryHandlerState> {
if (isNextRouterError(thrownValue)) {
// Re-throw if an expected internal Next.js router error occurs // Re-throw if an expected internal Next.js router error occurs
// this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment) // this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
throw error throw thrownValue
} }
return { error } return { error: { thrownValue } }
} }
static getDerivedStateFromProps( static getDerivedStateFromProps(
...@@ -75,7 +77,7 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -75,7 +77,7 @@ export class ErrorBoundaryHandler extends React.Component<
// the error boundary and instead should fallback // the error boundary and instead should fallback
// to a hard navigation to attempt recovering // to a hard navigation to attempt recovering
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
if (error && handleHardNavError(error)) { if (error && handleHardNavError(error.thrownValue)) {
// clear error so we don't render anything // clear error so we don't render anything
return { return {
error: null, error: null,
...@@ -118,14 +120,16 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -118,14 +120,16 @@ export class ErrorBoundaryHandler extends React.Component<
//When it's bot request, segment level error boundary will keep rendering the children, //When it's bot request, segment level error boundary will keep rendering the children,
// the final error will be caught by the root error boundary and determine wether need to apply graceful degrade. // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.
if (this.state.error && !isBotUserAgent) { if (this.state.error && !isBotUserAgent) {
handleISRError({ error: this.state.error }) const thrownValue = this.state.error.thrownValue
handleISRError({ error: thrownValue })
return ( return (
<> <>
{this.props.errorStyles} {this.props.errorStyles}
{this.props.errorScripts} {this.props.errorScripts}
<this.props.errorComponent <this.props.errorComponent
error={this.state.error} // TODO(NAR-804): Docs say this is an Error object, but we don't guarantee that
error={thrownValue}
reset={this.reset} reset={this.reset}
unstable_retry={this.unstable_retry} unstable_retry={this.unstable_retry}
/> />
......
...@@ -77,7 +77,7 @@ class HTTPAccessFallbackErrorBoundary extends React.Component< ...@@ -77,7 +77,7 @@ class HTTPAccessFallbackErrorBoundary extends React.Component<
} }
} }
static getDerivedStateFromError(error: any) { static getDerivedStateFromError(error: unknown) {
if (isHTTPAccessFallbackError(error)) { if (isHTTPAccessFallbackError(error)) {
const httpStatus = getAccessFallbackHTTPStatus(error) const httpStatus = getAccessFallbackHTTPStatus(error)
return { return {
......
...@@ -3,7 +3,6 @@ import { createHrefFromUrl } from './router-reducer/create-href-from-url' ...@@ -3,7 +3,6 @@ import { createHrefFromUrl } from './router-reducer/create-href-from-url'
export function handleHardNavError(error: unknown): boolean { export function handleHardNavError(error: unknown): boolean {
if ( if (
error &&
typeof window !== 'undefined' && typeof window !== 'undefined' &&
window.next.__pendingUrl && window.next.__pendingUrl &&
createHrefFromUrl(new URL(window.location.href)) !== createHrefFromUrl(new URL(window.location.href)) !==
......
...@@ -44,7 +44,7 @@ export class RedirectErrorBoundary extends React.Component< ...@@ -44,7 +44,7 @@ export class RedirectErrorBoundary extends React.Component<
this.state = { redirect: null, redirectType: null } this.state = { redirect: null, redirectType: null }
} }
static getDerivedStateFromError(error: any) { static getDerivedStateFromError(error: unknown) {
if (isRedirectError(error)) { if (isRedirectError(error)) {
const url = getURLFromRedirectError(error) const url = getURLFromRedirectError(error)
const redirectType = getRedirectTypeFromError(error) const redirectType = getRedirectTypeFromError(error)
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
AppRouterContext, AppRouterContext,
type AppRouterInstance, type AppRouterInstance,
} from '../../../shared/lib/app-router-context.shared-runtime' } from '../../../shared/lib/app-router-context.shared-runtime'
import isError from '../../../lib/is-error'
type AppDevOverlayErrorBoundaryProps = { type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode children: React.ReactNode
...@@ -16,33 +17,25 @@ type AppDevOverlayErrorBoundaryProps = { ...@@ -16,33 +17,25 @@ type AppDevOverlayErrorBoundaryProps = {
} }
type AppDevOverlayErrorBoundaryState = { type AppDevOverlayErrorBoundaryState = {
reactError: unknown error: null | { thrownValue: unknown }
} }
function ErroredHtml({ function ErroredHtml({
globalError: [GlobalError, globalErrorStyles], globalError: [GlobalError, globalErrorStyles],
error, thrownValue,
reset, reset,
unstable_retry, unstable_retry,
}: { }: {
globalError: GlobalErrorState globalError: GlobalErrorState
error: unknown thrownValue: unknown
reset: () => void reset: () => void
unstable_retry: () => void unstable_retry: () => void
}) { }) {
if (!error) {
return (
<html>
<head />
<body />
</html>
)
}
return ( return (
<ErrorBoundary errorComponent={DefaultGlobalError}> <ErrorBoundary errorComponent={DefaultGlobalError}>
{globalErrorStyles} {globalErrorStyles}
<GlobalError <GlobalError
error={error} error={thrownValue}
reset={reset} reset={reset}
unstable_retry={unstable_retry} unstable_retry={unstable_retry}
/> />
...@@ -58,20 +51,23 @@ export class AppDevOverlayErrorBoundary extends PureComponent< ...@@ -58,20 +51,23 @@ export class AppDevOverlayErrorBoundary extends PureComponent<
declare context: AppRouterInstance | null declare context: AppRouterInstance | null
state: AppDevOverlayErrorBoundaryState = { state: AppDevOverlayErrorBoundaryState = {
reactError: null, error: null,
} }
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(
thrownValue: Error
): Partial<AppDevOverlayErrorBoundaryState> {
RuntimeErrorHandler.hadRuntimeError = true RuntimeErrorHandler.hadRuntimeError = true
return { return {
reactError: error, error: { thrownValue },
} }
} }
componentDidCatch(err: Error) { componentDidCatch(err: unknown) {
if ( if (
process.env.NODE_ENV === 'development' && process.env.NODE_ENV === 'development' &&
isError(err) &&
err.message === SEGMENT_EXPLORER_SIMULATED_ERROR_MESSAGE err.message === SEGMENT_EXPLORER_SIMULATED_ERROR_MESSAGE
) { ) {
return return
...@@ -87,22 +83,25 @@ export class AppDevOverlayErrorBoundary extends PureComponent< ...@@ -87,22 +83,25 @@ export class AppDevOverlayErrorBoundary extends PureComponent<
} }
reset = () => { reset = () => {
this.setState({ reactError: null }) this.setState({ error: null })
} }
render() { render() {
const { children, globalError } = this.props const { children, globalError } = this.props
const { reactError } = this.state const { error } = this.state
const fallback = ( if (error !== null) {
<ErroredHtml const thrownValue = error.thrownValue
globalError={globalError} return (
error={reactError} <ErroredHtml
reset={this.reset} globalError={globalError}
unstable_retry={this.unstable_retry} thrownValue={thrownValue}
/> reset={this.reset}
) unstable_retry={this.unstable_retry}
/>
)
}
return reactError !== null ? fallback : children return children
} }
} }
...@@ -3,21 +3,25 @@ import React from 'react' ...@@ -3,21 +3,25 @@ import React from 'react'
type PagesDevOverlayErrorBoundaryProps = { type PagesDevOverlayErrorBoundaryProps = {
children?: React.ReactNode children?: React.ReactNode
} }
type PagesDevOverlayErrorBoundaryState = { error: Error | null } type PagesDevOverlayErrorBoundaryState = {
hasError: boolean
}
export class PagesDevOverlayErrorBoundary extends React.PureComponent< export class PagesDevOverlayErrorBoundary extends React.PureComponent<
PagesDevOverlayErrorBoundaryProps, PagesDevOverlayErrorBoundaryProps,
PagesDevOverlayErrorBoundaryState PagesDevOverlayErrorBoundaryState
> { > {
state = { error: null } state = { hasError: false }
static getDerivedStateFromError(error: Error) { static getDerivedStateFromError(
return { error } _: unknown
): Partial<PagesDevOverlayErrorBoundaryState> {
return { hasError: true }
} }
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version. // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
render(): React.ReactNode { render(): React.ReactNode {
// The component has to be unmounted or else it would continue to error // The component has to be unmounted or else it would continue to error
return this.state.error ? null : this.props.children return this.state.hasError ? null : this.props.children
} }
} }
...@@ -9,7 +9,7 @@ export function ErrorFallback( ...@@ -9,7 +9,7 @@ export function ErrorFallback(
) { ) {
return ( return (
<> <>
<p id="error-boundary-message">{error.message}</p> <p id="error-boundary-message">{(error as Error).message}</p>
<p id="error-boundary-title">{props.title}</p> <p id="error-boundary-title">{props.title}</p>
<button id="reset" onClick={() => reset()}> <button id="reset" onClick={() => reset()}>
Reset Reset
......
'use client'
import { useState } from 'react'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
function Inner() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw null
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
function ErrorFallback(_props: {}, { error }: ErrorInfo) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
const Wrapped = unstable_catchError(ErrorFallback)
export default function Page() {
return (
<Wrapped>
<Inner />
</Wrapped>
)
}
'use client'
import { useState } from 'react'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
function Inner() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw undefined
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
function ErrorFallback(_props: {}, { error }: ErrorInfo) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
const Wrapped = unstable_catchError(ErrorFallback)
export default function Page() {
return (
<Wrapped>
<Inner />
</Wrapped>
)
}
...@@ -8,7 +8,7 @@ export function ErrorFallback( ...@@ -8,7 +8,7 @@ export function ErrorFallback(
) { ) {
return ( return (
<> <>
<p id="error-boundary-message">{error.message}</p> <p id="error-boundary-message">{(error as Error).message}</p>
<p id="error-boundary-title">{props.title}</p> <p id="error-boundary-title">{props.title}</p>
<button id="reset" onClick={() => reset()}> <button id="reset" onClick={() => reset()}>
Reset Reset
......
'use client'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
function ErrorFallback(_props: {}, { error }: ErrorInfo) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
export default unstable_catchError(ErrorFallback)
import { Suspense } from 'react'
import { connection } from 'next/server'
import ErrorWrapper from './error-wrapper'
export default function Page() {
return (
<ErrorWrapper>
<Suspense>
<PageImpl />
</Suspense>
</ErrorWrapper>
)
}
async function PageImpl(): Promise<never> {
await connection()
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw null
}
'use client'
import type { ErrorInfo } from 'next/error'
import { unstable_catchError } from 'next/error'
function ErrorFallback(_props: {}, { error }: ErrorInfo) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
export default unstable_catchError(ErrorFallback)
import { Suspense } from 'react'
import { connection } from 'next/server'
import ErrorWrapper from './error-wrapper'
export default function Page() {
return (
<ErrorWrapper>
<Suspense>
<PageImpl />
</Suspense>
</ErrorWrapper>
)
}
async function PageImpl(): Promise<never> {
await connection()
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw undefined
}
...@@ -69,6 +69,48 @@ describe('app-dir - unstable_catchError', () => { ...@@ -69,6 +69,48 @@ describe('app-dir - unstable_catchError', () => {
expect(await browser.elementByCss('#recover').text()).toBe('Recovered') expect(await browser.elementByCss('#recover').text()).toBe('Recovered')
}) })
it('should render fallback when undefined is thrown from a Client Component', async () => {
const browser = await next.browser('/client-component/throw-undefined')
await browser.elementByCss('#error-trigger-button').click()
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe('An error occurred: undefined')
})
it('should render fallback when null is thrown from a Client Component', async () => {
const browser = await next.browser('/client-component/throw-null')
await browser.elementByCss('#error-trigger-button').click()
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe('An error occurred: null')
})
it('should render fallback when undefined is thrown from a Server Component', async () => {
const browser = await next.browser('/server-component/throw-undefined')
// non-error values thrown during rendering get wrapped in an Error when transported over RSC.
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe(
isNextDev
? 'An error occurred: Error: undefined'
: 'An error occurred: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
)
})
it('should render fallback when null is thrown from a Server Component', async () => {
const browser = await next.browser('/server-component/throw-null')
// non-error values thrown during rendering get wrapped in an Error when transported over RSC.
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe(
isNextDev
? 'An error occurred: Error: null'
: 'An error occurred: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
)
})
it('should recover after reset on Pages Router', async () => { it('should recover after reset on Pages Router', async () => {
const browser = await next.browser('/pages-router') const browser = await next.browser('/pages-router')
......
...@@ -9,7 +9,7 @@ function ErrorFallback( ...@@ -9,7 +9,7 @@ function ErrorFallback(
return ( return (
<> <>
<p id="pages-error-message">{error.message}</p> <p id="pages-error-message">{(error as Error).message}</p>
<button <button
id="pages-reset" id="pages-reset"
onClick={() => { onClick={() => {
......
'use client'
export default function ErrorBoundary({ error }) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
'use client'
import { useState } from 'react'
export default function Page() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw null
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
'use client'
export default function ErrorBoundary({ error }) {
return <p id="error-boundary-message">{`An error occurred: ${error}`}</p>
}
'use client'
import { useState } from 'react'
export default function Page() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw undefined
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
'use client'
export default function ErrorBoundary({ error }) {
return (
<div>
<p id="error-boundary-message">{`An error occurred: ${error}`}</p>
<p id="error-boundary-digest">{`${error?.digest}`}</p>
</div>
)
}
'use client'
export default function ErrorBoundary({ error }) {
return (
<div>
<p id="error-boundary-message">{`An error occurred: ${error}`}</p>
<p id="error-boundary-digest">{`${error?.digest}`}</p>
</div>
)
}
...@@ -39,6 +39,44 @@ describe('app-dir - errors', () => { ...@@ -39,6 +39,44 @@ describe('app-dir - errors', () => {
expect(pageErrors).toEqual([]) expect(pageErrors).toEqual([])
}) })
it('should trigger error component when undefined is thrown from a client component in the browser', async () => {
const pageErrors: unknown[] = []
const browser = await next.browser('/client-component/throw-undefined', {
beforePageLoad: (page) => {
page.on('pageerror', (error: unknown) => {
pageErrors.push(error)
})
},
})
await browser.elementByCss('#error-trigger-button').click()
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe('An error occurred: undefined')
// Handled by custom error boundary.
expect(pageErrors).toEqual([])
})
it('should trigger error component when null is thrown from a client component in the browser', async () => {
const pageErrors: unknown[] = []
const browser = await next.browser('/client-component/throw-null', {
beforePageLoad: (page) => {
page.on('pageerror', (error: unknown) => {
pageErrors.push(error)
})
},
})
await browser.elementByCss('#error-trigger-button').click()
expect(
await browser.waitForElementByCss('#error-boundary-message').text()
).toBe('An error occurred: null')
// Handled by custom error boundary.
expect(pageErrors).toEqual([])
})
it('should trigger error component when an error happens during server components rendering', async () => { it('should trigger error component when an error happens during server components rendering', async () => {
const pageErrors: unknown[] = [] const pageErrors: unknown[] = []
const browser = await next.browser('/server-component', { const browser = await next.browser('/server-component', {
...@@ -97,12 +135,14 @@ describe('app-dir - errors', () => { ...@@ -97,12 +135,14 @@ describe('app-dir - errors', () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
const browser = await next.browser('/server-component/throw-undefined') const browser = await next.browser('/server-component/throw-undefined')
// Non-error values thrown during rendering get wrapped in an Error when transported over RSC,
// so we expect an error object with a digest.
expect( expect(
await browser.waitForElementByCss('#error-boundary-message').text() await browser.waitForElementByCss('#error-boundary-message').text()
).toBe( ).toBe(
isNextDev isNextDev
? 'undefined' ? 'An error occurred: Error: undefined'
: 'Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' : 'An error occurred: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
) )
expect( expect(
await browser.waitForElementByCss('#error-boundary-digest').text() await browser.waitForElementByCss('#error-boundary-digest').text()
...@@ -132,12 +172,15 @@ describe('app-dir - errors', () => { ...@@ -132,12 +172,15 @@ describe('app-dir - errors', () => {
const outputIndex = next.cliOutput.length const outputIndex = next.cliOutput.length
const browser = await next.browser('/server-component/throw-null') const browser = await next.browser('/server-component/throw-null')
// Non-error values thrown during rendering get wrapped in an Error when transported over RSC,
// so we expect an error object with a digest.
expect( expect(
await browser.waitForElementByCss('#error-boundary-message').text() await browser.waitForElementByCss('#error-boundary-message').text()
).toBe( ).toBe(
isNextDev isNextDev
? 'null' ? 'An error occurred: Error: null'
: 'Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' : 'An error occurred: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
) )
expect( expect(
await browser.waitForElementByCss('#error-boundary-digest').text() await browser.waitForElementByCss('#error-boundary-digest').text()
......
'use client'
import { useState } from 'react'
export default function Page() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw null
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
'use client'
import { useState } from 'react'
export default function Page() {
const [clicked, setClicked] = useState(false)
if (clicked) {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw undefined
}
return (
<button
id="error-trigger-button"
onClick={() => {
setClicked(true)
}}
>
Trigger Error!
</button>
)
}
...@@ -6,7 +6,7 @@ export default function GlobalError({ error }) { ...@@ -6,7 +6,7 @@ export default function GlobalError({ error }) {
<head></head> <head></head>
<body> <body>
<h1>Global Error</h1> <h1>Global Error</h1>
<p id="error">{`Global error: ${error?.message}`}</p> <p id="error">{`Global error: ${error}`}</p>
{error?.digest && <p id="digest">{error?.digest}</p>} {error?.digest && <p id="digest">{error?.digest}</p>}
</body> </body>
</html> </html>
......
export default function page() {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw null
}
export default function page() {
// eslint-disable-next-line no-throw-literal -- testing bad values on purpose
throw undefined
}
...@@ -28,7 +28,7 @@ describe('app dir - global-error', () => { ...@@ -28,7 +28,7 @@ describe('app dir - global-error', () => {
`) `)
} }
expect(await browser.elementByCss('#error').text()).toBe( expect(await browser.elementByCss('#error').text()).toBe(
'Global error: Client error' 'Global error: Error: Client error'
) )
}) })
...@@ -54,8 +54,8 @@ describe('app dir - global-error', () => { ...@@ -54,8 +54,8 @@ describe('app dir - global-error', () => {
// Show original error message in dev mode, but hide with the react fallback RSC error message in production mode // Show original error message in dev mode, but hide with the react fallback RSC error message in production mode
expect(await browser.elementByCss('#error').text()).toBe( expect(await browser.elementByCss('#error').text()).toBe(
isNextDev isNextDev
? 'Global error: server page error' ? 'Global error: Error: server page error'
: 'Global error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' : 'Global error: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
) )
expect(await browser.elementByCss('#digest').text()).toMatch(/\w+/) expect(await browser.elementByCss('#digest').text()).toMatch(/\w+/)
}) })
...@@ -80,12 +80,58 @@ describe('app dir - global-error', () => { ...@@ -80,12 +80,58 @@ describe('app dir - global-error', () => {
} }
expect(await browser.elementByCss('h1').text()).toBe('Global Error') expect(await browser.elementByCss('h1').text()).toBe('Global Error')
expect(await browser.elementByCss('#error').text()).toBe( expect(await browser.elementByCss('#error').text()).toBe(
'Global error: client page error' 'Global error: Error: client page error'
) )
expect(await browser.hasElementByCssSelector('#digest')).toBeFalsy() expect(await browser.hasElementByCssSelector('#digest')).toBeFalsy()
}) })
it('should render global error when undefined is thrown in a server component', async () => {
const browser = await next.browser('/rsc-throw-undefined')
// Non-error values thrown during RSC render get wrapped in an Error when transported.
expect(await browser.waitForElementByCss('#error').text()).toBe(
isNextDev
? 'Global error: Error: undefined'
: 'Global error: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
)
expect(await browser.elementByCss('h1').text()).toBe('Global Error')
})
it('should render global error when null is thrown in a server component', async () => {
const browser = await next.browser('/rsc-throw-null')
// Non-error values thrown during RSC render get wrapped in an Error when transported.
expect(await browser.waitForElementByCss('#error').text()).toBe(
isNextDev
? 'Global error: Error: null'
: 'Global error: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
)
expect(await browser.elementByCss('h1').text()).toBe('Global Error')
})
it('should render global error when undefined is thrown in a client component', async () => {
const browser = await next.browser('/client-throw-undefined')
await browser
.waitForElementByCss('#error-trigger-button')
.elementByCss('#error-trigger-button')
.click()
expect(await browser.waitForElementByCss('#error').text()).toBe(
'Global error: undefined'
)
expect(await browser.elementByCss('h1').text()).toBe('Global Error')
})
it('should render global error when null is thrown in a client component', async () => {
const browser = await next.browser('/client-throw-null')
await browser
.waitForElementByCss('#error-trigger-button')
.elementByCss('#error-trigger-button')
.click()
expect(await browser.waitForElementByCss('#error').text()).toBe(
'Global error: null'
)
expect(await browser.elementByCss('h1').text()).toBe('Global Error')
})
it('should catch metadata error in error boundary if presented', async () => { it('should catch metadata error in error boundary if presented', async () => {
const browser = await next.browser('/metadata-error-with-boundary') const browser = await next.browser('/metadata-error-with-boundary')
...@@ -116,8 +162,8 @@ describe('app dir - global-error', () => { ...@@ -116,8 +162,8 @@ describe('app dir - global-error', () => {
expect(await browser.elementByCss('h1').text()).toBe('Global Error') expect(await browser.elementByCss('h1').text()).toBe('Global Error')
expect(await browser.elementByCss('#error').text()).toBe( expect(await browser.elementByCss('#error').text()).toBe(
isNextDev isNextDev
? 'Global error: Metadata error' ? 'Global error: Error: Metadata error'
: 'Global error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.' : 'Global error: Error: Minified React error #441; visit https://react.dev/errors/441 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.'
) )
}) })
...@@ -140,7 +186,7 @@ describe('app dir - global-error', () => { ...@@ -140,7 +186,7 @@ describe('app dir - global-error', () => {
} }
expect(await browser.elementByCss('h1').text()).toBe('Global Error') expect(await browser.elementByCss('h1').text()).toBe('Global Error')
expect(await browser.elementByCss('#error').text()).toBe( expect(await browser.elementByCss('#error').text()).toBe(
'Global error: nested error' 'Global error: Error: nested error'
) )
}) })
}) })
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