Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
064970e0
Unverified
Commit
064970e0
authored
Oct 23, 2024
by
Jiachi Liu
Committed by
GitHub
Oct 23, 2024
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
feat: stitch errors with react owner stack (#70393)
parent
6fba7b24
Show whitespace changes
Inline
Side-by-side
Showing
32 changed files
with
661 additions
and
201 deletions
+661
-201
next_config.rs
crates/next-core/src/next_config.rs
+8
-0
next_import_map.rs
crates/next-core/src/next_import_map.rs
+14
-7
define-env-plugin.ts
packages/next/src/build/webpack/plugins/define-env-plugin.ts
+3
-0
app-index.tsx
packages/next/src/client/app-index.tsx
+16
-1
intercept-console-error.ts
.../src/client/components/globals/intercept-console-error.ts
+1
-1
ReactDevOverlay.tsx
...ient/components/react-dev-overlay/app/ReactDevOverlay.tsx
+9
-22
hot-reloader-client.tsx
.../components/react-dev-overlay/app/hot-reloader-client.tsx
+10
-12
client-entry.tsx
.../src/client/components/react-dev-overlay/client-entry.tsx
+0
-1
Errors.tsx
...omponents/react-dev-overlay/internal/container/Errors.tsx
+5
-6
console-error.ts
...nents/react-dev-overlay/internal/helpers/console-error.ts
+14
-5
parse-component-stack.ts
...act-dev-overlay/internal/helpers/parse-component-stack.ts
+1
-0
stitched-error.ts
...ents/react-dev-overlay/internal/helpers/stitched-error.ts
+42
-0
use-error-handler.ts
...s/react-dev-overlay/internal/helpers/use-error-handler.ts
+30
-38
index.tsx
packages/next/src/client/index.tsx
+1
-2
on-recoverable-error.ts
packages/next/src/client/on-recoverable-error.ts
+0
-27
app-router.ts
...ages/next/src/client/react-client-callbacks/app-router.ts
+96
-0
report-global-error.ts
.../src/client/react-client-callbacks/report-global-error.ts
+8
-0
shared.ts
packages/next/src/client/react-client-callbacks/shared.ts
+21
-0
needs-experimental-react.ts
packages/next/src/lib/needs-experimental-react.ts
+2
-1
config-schema.ts
packages/next/src/server/config-schema.ts
+1
-0
config-shared.ts
packages/next/src/server/config-shared.ts
+7
-0
ReactRefreshLogBox.test.ts
test/development/acceptance-app/ReactRefreshLogBox.test.ts
+26
-32
ReactRefreshLogBox.test.ts
test/development/acceptance/ReactRefreshLogBox.test.ts
+1
-5
index.test.ts
test/development/app-dir/dynamic-error-trace/index.test.ts
+16
-32
page.js
...evelopment/app-dir/owner-stack/app/browser/caught/page.js
+44
-0
page.js
...nt/app-dir/owner-stack/app/browser/reject-promise/page.js
+16
-0
page.js
...elopment/app-dir/owner-stack/app/browser/uncaught/page.js
+16
-0
layout.js
test/development/app-dir/owner-stack/app/layout.js
+7
-0
page.js
test/development/app-dir/owner-stack/app/ssr/page.js
+14
-0
next.config.js
test/development/app-dir/owner-stack/next.config.js
+10
-0
owner-stack.test.ts
test/development/app-dir/owner-stack/owner-stack.test.ts
+222
-0
next-test-utils.ts
test/lib/next-test-utils.ts
+0
-9
No files found.
crates/next-core/src/next_config.rs
View file @
064970e0
...
@@ -561,6 +561,7 @@ pub struct ExperimentalConfig {
...
@@ -561,6 +561,7 @@ pub struct ExperimentalConfig {
/// directory.
/// directory.
ppr
:
Option
<
ExperimentalPartialPrerendering
>
,
ppr
:
Option
<
ExperimentalPartialPrerendering
>
,
taint
:
Option
<
bool
>
,
taint
:
Option
<
bool
>
,
react_owner_stack
:
Option
<
bool
>
,
#[serde(rename
=
"dynamicIO"
)]
#[serde(rename
=
"dynamicIO"
)]
dynamic_io
:
Option
<
bool
>
,
dynamic_io
:
Option
<
bool
>
,
proxy_timeout
:
Option
<
f64
>
,
proxy_timeout
:
Option
<
f64
>
,
...
@@ -1148,6 +1149,13 @@ impl NextConfig {
...
@@ -1148,6 +1149,13 @@ impl NextConfig {
Vc
::
cell
(
self
.experimental.taint
.unwrap_or
(
false
))
Vc
::
cell
(
self
.experimental.taint
.unwrap_or
(
false
))
}
}
#[turbo_tasks
::
function]
pub
async
fn
enable_react_owner_stack
(
self
:
Vc
<
Self
>
)
->
Result
<
Vc
<
bool
>>
{
Ok
(
Vc
::
cell
(
self
.await
?
.experimental.react_owner_stack
.unwrap_or
(
false
),
))
}
#[turbo_tasks
::
function]
#[turbo_tasks
::
function]
pub
fn
use_swc_css
(
&
self
)
->
Vc
<
bool
>
{
pub
fn
use_swc_css
(
&
self
)
->
Vc
<
bool
>
{
Vc
::
cell
(
Vc
::
cell
(
...
...
crates/next-core/src/next_import_map.rs
View file @
064970e0
...
@@ -116,8 +116,10 @@ pub async fn get_next_client_import_map(
...
@@ -116,8 +116,10 @@ pub async fn get_next_client_import_map(
match
ty
.into_value
()
{
match
ty
.into_value
()
{
ClientContextType
::
Pages
{
..
}
=>
{}
ClientContextType
::
Pages
{
..
}
=>
{}
ClientContextType
::
App
{
app_dir
}
=>
{
ClientContextType
::
App
{
app_dir
}
=>
{
let
react_flavor
=
let
react_flavor
=
if
*
next_config
.enable_ppr
()
.await
?
if
*
next_config
.enable_ppr
()
.await
?
||
*
next_config
.enable_taint
()
.await
?
{
||
*
next_config
.enable_taint
()
.await
?
||
*
next_config
.enable_react_owner_stack
()
.await
?
{
"-experimental"
"-experimental"
}
else
{
}
else
{
""
""
...
@@ -683,7 +685,12 @@ async fn rsc_aliases(
...
@@ -683,7 +685,12 @@ async fn rsc_aliases(
)
->
Result
<
()
>
{
)
->
Result
<
()
>
{
let
ppr
=
*
next_config
.enable_ppr
()
.await
?
;
let
ppr
=
*
next_config
.enable_ppr
()
.await
?
;
let
taint
=
*
next_config
.enable_taint
()
.await
?
;
let
taint
=
*
next_config
.enable_taint
()
.await
?
;
let
react_channel
=
if
ppr
||
taint
{
"-experimental"
}
else
{
""
};
let
react_owner_stack
=
*
next_config
.enable_react_owner_stack
()
.await
?
;
let
react_channel
=
if
ppr
||
taint
||
react_owner_stack
{
"-experimental"
}
else
{
""
};
let
react_client_package
=
get_react_client_package
(
&
next_config
)
.await
?
;
let
react_client_package
=
get_react_client_package
(
&
next_config
)
.await
?
;
let
mut
alias
=
FxIndexMap
::
default
();
let
mut
alias
=
FxIndexMap
::
default
();
...
...
packages/next/src/build/webpack/plugins/define-env-plugin.ts
View file @
064970e0
...
@@ -185,6 +185,9 @@ export function getDefineEnv({
...
@@ -185,6 +185,9 @@ export function getDefineEnv({
),
),
'process.env.__NEXT_PPR'
:
checkIsAppPPREnabled
(
config
.
experimental
.
ppr
),
'process.env.__NEXT_PPR'
:
checkIsAppPPREnabled
(
config
.
experimental
.
ppr
),
'process.env.__NEXT_DYNAMIC_IO'
:
!!
config
.
experimental
.
dynamicIO
,
'process.env.__NEXT_DYNAMIC_IO'
:
!!
config
.
experimental
.
dynamicIO
,
'process.env.__NEXT_REACT_OWNER_STACK'
:
Boolean
(
config
.
experimental
.
reactOwnerStack
),
'process.env.__NEXT_AFTER'
:
config
.
experimental
.
after
??
false
,
'process.env.__NEXT_AFTER'
:
config
.
experimental
.
after
??
false
,
'process.env.NEXT_DEPLOYMENT_ID'
:
config
.
deploymentId
||
false
,
'process.env.NEXT_DEPLOYMENT_ID'
:
config
.
deploymentId
||
false
,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX'
:
fetchCacheKeyPrefix
??
''
,
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX'
:
fetchCacheKeyPrefix
??
''
,
...
...
packages/next/src/client/app-index.tsx
View file @
064970e0
...
@@ -9,7 +9,11 @@ import React, { use } from 'react'
...
@@ -9,7 +9,11 @@ import React, { use } from 'react'
// eslint-disable-next-line import/no-extraneous-dependencies
// eslint-disable-next-line import/no-extraneous-dependencies
import
{
createFromReadableStream
}
from
'react-server-dom-webpack/client'
import
{
createFromReadableStream
}
from
'react-server-dom-webpack/client'
import
{
HeadManagerContext
}
from
'../shared/lib/head-manager-context.shared-runtime'
import
{
HeadManagerContext
}
from
'../shared/lib/head-manager-context.shared-runtime'
import
{
onRecoverableError
}
from
'./on-recoverable-error'
import
{
onRecoverableError
}
from
'./react-client-callbacks/shared'
import
{
onCaughtError
,
onUncaughtError
,
}
from
'./react-client-callbacks/app-router'
import
{
callServer
}
from
'./app-call-server'
import
{
callServer
}
from
'./app-call-server'
import
{
findSourceMapURL
}
from
'./app-find-source-map-url'
import
{
findSourceMapURL
}
from
'./app-find-source-map-url'
import
{
import
{
...
@@ -23,6 +27,8 @@ import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runt
...
@@ -23,6 +27,8 @@ import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runt
/// <reference types="react-dom/experimental" />
/// <reference types="react-dom/experimental" />
const
isReactOwnerStackEnabled
=
!!
process
.
env
.
__NEXT_REACT_OWNER_STACK
const
appElement
:
HTMLElement
|
Document
|
null
=
document
const
appElement
:
HTMLElement
|
Document
|
null
=
document
const
encoder
=
new
TextEncoder
()
const
encoder
=
new
TextEncoder
()
...
@@ -227,8 +233,17 @@ export function hydrate() {
...
@@ -227,8 +233,17 @@ export function hydrate() {
const
rootLayoutMissingTags
=
window
.
__next_root_layout_missing_tags
const
rootLayoutMissingTags
=
window
.
__next_root_layout_missing_tags
const
hasMissingTags
=
!!
rootLayoutMissingTags
?.
length
const
hasMissingTags
=
!!
rootLayoutMissingTags
?.
length
const
errorCallbacks
=
isReactOwnerStackEnabled
&&
process
.
env
.
NODE_ENV
!==
'production'
?
{
onCaughtError
,
onUncaughtError
,
}
:
undefined
const
options
=
{
const
options
=
{
onRecoverableError
,
onRecoverableError
,
...
errorCallbacks
,
}
satisfies
ReactDOMClient
.
RootOptions
}
satisfies
ReactDOMClient
.
RootOptions
const
isError
=
const
isError
=
document
.
documentElement
.
id
===
'__next_error__'
||
hasMissingTags
document
.
documentElement
.
id
===
'__next_error__'
||
hasMissingTags
...
...
packages/next/src/client/components/globals/intercept-console-error.ts
View file @
064970e0
...
@@ -2,7 +2,7 @@ import isError from '../../../lib/is-error'
...
@@ -2,7 +2,7 @@ import isError from '../../../lib/is-error'
import
{
isNextRouterError
}
from
'../is-next-router-error'
import
{
isNextRouterError
}
from
'../is-next-router-error'
import
{
handleClientError
}
from
'../react-dev-overlay/internal/helpers/use-error-handler'
import
{
handleClientError
}
from
'../react-dev-overlay/internal/helpers/use-error-handler'
const
originConsoleError
=
window
.
console
.
error
export
const
originConsoleError
=
window
.
console
.
error
// Patch console.error to collect information about hydration errors
// Patch console.error to collect information about hydration errors
export
function
patchConsoleError
()
{
export
function
patchConsoleError
()
{
...
...
packages/next/src/client/components/react-dev-overlay/app/ReactDevOverlay.tsx
View file @
064970e0
import
*
as
React
from
'react'
import
React
from
'react'
import
{
ACTION_UNHANDLED_ERROR
,
type
OverlayState
}
from
'../shared'
import
{
ACTION_UNHANDLED_ERROR
,
type
OverlayState
}
from
'../shared'
import
{
ShadowPortal
}
from
'../internal/components/ShadowPortal'
import
{
ShadowPortal
}
from
'../internal/components/ShadowPortal'
import
{
BuildError
}
from
'../internal/container/BuildError'
import
{
BuildError
}
from
'../internal/container/BuildError'
import
{
Errors
}
from
'../internal/container/Errors'
import
{
Errors
,
type
SupportedErrorEvent
}
from
'../internal/container/Errors'
import
{
StaticIndicator
}
from
'../internal/container/StaticIndicator'
import
type
{
SupportedErrorEvent
}
from
'../internal/container/Errors'
import
{
parseStack
}
from
'../internal/helpers/parse-stack'
import
{
parseStack
}
from
'../internal/helpers/parse-stack'
import
{
StaticIndicator
}
from
'../internal/container/StaticIndicator'
import
{
Base
}
from
'../internal/styles/Base'
import
{
Base
}
from
'../internal/styles/Base'
import
{
ComponentStyles
}
from
'../internal/styles/ComponentStyles'
import
{
ComponentStyles
}
from
'../internal/styles/ComponentStyles'
import
{
CssReset
}
from
'../internal/styles/CssReset'
import
{
CssReset
}
from
'../internal/styles/CssReset'
import
{
RootLayoutMissingTagsError
}
from
'../internal/container/root-layout-missing-tags-error'
import
{
RootLayoutMissingTagsError
}
from
'../internal/container/root-layout-missing-tags-error'
import
type
{
Dispatcher
}
from
'./hot-reloader-client'
import
type
{
Dispatcher
}
from
'./hot-reloader-client'
import
{
RuntimeErrorHandler
}
from
'../internal/helpers/runtime-error-handler'
interface
ReactDevOverlayState
{
interface
ReactDevOverlayState
{
reactError
:
SupportedErrorEvent
|
null
reactError
:
SupportedErrorEvent
|
null
...
@@ -21,7 +20,6 @@ export default class ReactDevOverlay extends React.PureComponent<
...
@@ -21,7 +20,6 @@ export default class ReactDevOverlay extends React.PureComponent<
state
:
OverlayState
state
:
OverlayState
dispatcher
?:
Dispatcher
dispatcher
?:
Dispatcher
children
:
React
.
ReactNode
children
:
React
.
ReactNode
onReactError
:
(
error
:
Error
)
=>
void
},
},
ReactDevOverlayState
ReactDevOverlayState
>
{
>
{
...
@@ -29,6 +27,8 @@ export default class ReactDevOverlay extends React.PureComponent<
...
@@ -29,6 +27,8 @@ export default class ReactDevOverlay extends React.PureComponent<
static
getDerivedStateFromError
(
error
:
Error
):
ReactDevOverlayState
{
static
getDerivedStateFromError
(
error
:
Error
):
ReactDevOverlayState
{
if
(
!
error
.
stack
)
return
{
reactError
:
null
}
if
(
!
error
.
stack
)
return
{
reactError
:
null
}
RuntimeErrorHandler
.
hadRuntimeError
=
true
return
{
return
{
reactError
:
{
reactError
:
{
id
:
0
,
id
:
0
,
...
@@ -41,10 +41,6 @@ export default class ReactDevOverlay extends React.PureComponent<
...
@@ -41,10 +41,6 @@ export default class ReactDevOverlay extends React.PureComponent<
}
}
}
}
componentDidCatch
(
componentErr
:
Error
)
{
this
.
props
.
onReactError
(
componentErr
)
}
render
()
{
render
()
{
const
{
state
,
children
,
dispatcher
}
=
this
.
props
const
{
state
,
children
,
dispatcher
}
=
this
.
props
const
{
reactError
}
=
this
.
state
const
{
reactError
}
=
this
.
state
...
@@ -79,20 +75,11 @@ export default class ReactDevOverlay extends React.PureComponent<
...
@@ -79,20 +75,11 @@ export default class ReactDevOverlay extends React.PureComponent<
/>
/>
)
:
(
)
:
(
<>
<>
{
reactError
?
(
{
hasRuntimeErrors
?
(
<
Errors
isAppDir=
{
true
}
versionInfo=
{
state
.
versionInfo
}
initialDisplayState=
"fullscreen"
errors=
{
[
reactError
]
}
hasStaticIndicator=
{
hasStaticIndicator
}
debugInfo=
{
debugInfo
}
/>
)
:
hasRuntimeErrors
?
(
<
Errors
<
Errors
isAppDir=
{
true
}
isAppDir=
{
true
}
initialDisplayState=
"minimized"
initialDisplayState=
{
reactError
?
'fullscreen'
:
'minimized'
}
errors=
{
state
.
errors
}
errors=
{
reactError
?
[
reactError
]
:
state
.
errors
}
versionInfo=
{
state
.
versionInfo
}
versionInfo=
{
state
.
versionInfo
}
hasStaticIndicator=
{
hasStaticIndicator
}
hasStaticIndicator=
{
hasStaticIndicator
}
debugInfo=
{
debugInfo
}
debugInfo=
{
debugInfo
}
...
...
packages/next/src/client/components/react-dev-overlay/app/hot-reloader-client.tsx
View file @
064970e0
...
@@ -37,6 +37,7 @@ import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
...
@@ -37,6 +37,7 @@ import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import
type
{
HydrationErrorState
}
from
'../internal/helpers/hydration-error-info'
import
type
{
HydrationErrorState
}
from
'../internal/helpers/hydration-error-info'
import
type
{
DebugInfo
}
from
'../types'
import
type
{
DebugInfo
}
from
'../types'
import
{
useUntrackedPathname
}
from
'../../navigation-untracked'
import
{
useUntrackedPathname
}
from
'../../navigation-untracked'
import
{
getReactStitchedError
}
from
'../internal/helpers/stitched-error'
export
interface
Dispatcher
{
export
interface
Dispatcher
{
onBuildOk
():
void
onBuildOk
():
void
...
@@ -563,10 +564,12 @@ export default function HotReload({
...
@@ -563,10 +564,12 @@ export default function HotReload({
const
componentStackTrace
=
const
componentStackTrace
=
(
error
as
any
).
_componentStack
||
errorDetails
?.
componentStack
(
error
as
any
).
_componentStack
||
errorDetails
?.
componentStack
const
warning
=
errorDetails
?.
warning
const
warning
=
errorDetails
?.
warning
const
stitchedError
=
getReactStitchedError
(
error
)
dispatch
({
dispatch
({
type
:
ACTION_UNHANDLED_ERROR
,
type
:
ACTION_UNHANDLED_ERROR
,
reason
:
e
rror
,
reason
:
stitchedE
rror
,
frames
:
parseStack
(
error
.
stack
),
frames
:
parseStack
(
stitchedError
.
stack
||
''
),
componentStackFrames
:
componentStackFrames
:
typeof
componentStackTrace
===
'string'
typeof
componentStackTrace
===
'string'
?
parseComponentStack
(
componentStackTrace
)
?
parseComponentStack
(
componentStackTrace
)
...
@@ -576,19 +579,18 @@ export default function HotReload({
...
@@ -576,19 +579,18 @@ export default function HotReload({
},
},
[
dispatch
]
[
dispatch
]
)
)
const
handleOnUnhandledRejection
=
useCallback
(
const
handleOnUnhandledRejection
=
useCallback
(
(
reason
:
Error
):
void
=>
{
(
reason
:
Error
):
void
=>
{
const
stitchedError
=
getReactStitchedError
(
reason
)
dispatch
({
dispatch
({
type
:
ACTION_UNHANDLED_REJECTION
,
type
:
ACTION_UNHANDLED_REJECTION
,
reason
:
reason
,
reason
:
stitchedError
,
frames
:
parseStack
(
reason
.
stack
!
),
frames
:
parseStack
(
stitchedError
.
stack
||
''
),
})
})
},
},
[
dispatch
]
[
dispatch
]
)
)
const
handleOnReactError
=
useCallback
(()
=>
{
RuntimeErrorHandler
.
hadRuntimeError
=
true
},
[])
useErrorHandler
(
handleOnUnhandledError
,
handleOnUnhandledRejection
)
useErrorHandler
(
handleOnUnhandledError
,
handleOnUnhandledRejection
)
const
webSocketRef
=
useWebsocket
(
assetPrefix
)
const
webSocketRef
=
useWebsocket
(
assetPrefix
)
...
@@ -674,11 +676,7 @@ export default function HotReload({
...
@@ -674,11 +676,7 @@ export default function HotReload({
])
])
return
(
return
(
<
ReactDevOverlay
<
ReactDevOverlay
state=
{
state
}
dispatcher=
{
dispatcher
}
>
onReactError=
{
handleOnReactError
}
state=
{
state
}
dispatcher=
{
dispatcher
}
>
{
children
}
{
children
}
</
ReactDevOverlay
>
</
ReactDevOverlay
>
)
)
...
...
packages/next/src/client/components/react-dev-overlay/client-entry.tsx
View file @
064970e0
...
@@ -42,7 +42,6 @@ export function createDevOverlayElement(reactEl: React.ReactElement) {
...
@@ -42,7 +42,6 @@ export function createDevOverlayElement(reactEl: React.ReactElement) {
<
FallbackLayout
>
<
FallbackLayout
>
<
ReactDevOverlay
<
ReactDevOverlay
state=
{
{
...
INITIAL_OVERLAY_STATE
,
rootLayoutMissingTags
}
}
state=
{
{
...
INITIAL_OVERLAY_STATE
,
rootLayoutMissingTags
}
}
onReactError=
{
()
=>
{}
}
>
>
{
reactEl
}
{
reactEl
}
</
ReactDevOverlay
>
</
ReactDevOverlay
>
...
...
packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx
View file @
064970e0
...
@@ -31,7 +31,7 @@ import {
...
@@ -31,7 +31,7 @@ import {
}
from
'../helpers/hydration-error-info'
}
from
'../helpers/hydration-error-info'
import
{
NodejsInspectorCopyButton
}
from
'../components/nodejs-inspector'
import
{
NodejsInspectorCopyButton
}
from
'../components/nodejs-inspector'
import
{
CopyButton
}
from
'../components/copy-button'
import
{
CopyButton
}
from
'../components/copy-button'
import
{
ConsoleError
}
from
'../helpers/console-error'
import
{
isUnhandledConsoleOrRejection
}
from
'../helpers/console-error'
export
type
SupportedErrorEvent
=
{
export
type
SupportedErrorEvent
=
{
id
:
number
id
:
number
...
@@ -61,11 +61,11 @@ function ErrorDescription({
...
@@ -61,11 +61,11 @@ function ErrorDescription({
error
:
Error
error
:
Error
hydrationWarning
:
string
|
null
hydrationWarning
:
string
|
null
})
{
})
{
const
is
FromConsoleError
=
error
instanceof
ConsoleError
const
is
UnhandledError
=
isUnhandledConsoleOrRejection
(
error
)
// If there's hydration warning or console error, skip displaying the error name
// If there's hydration warning or console error, skip displaying the error name
return
(
return
(
<>
<>
{
is
FromConsole
Error
||
hydrationWarning
?
''
:
error
.
name
+
': '
}
{
is
Unhandled
Error
||
hydrationWarning
?
''
:
error
.
name
+
': '
}
<
HotlinkedText
<
HotlinkedText
text=
{
hydrationWarning
||
error
.
message
}
text=
{
hydrationWarning
||
error
.
message
}
matcher=
{
isNextjsLink
}
matcher=
{
isNextjsLink
}
...
@@ -257,8 +257,7 @@ export function Errors({
...
@@ -257,8 +257,7 @@ export function Errors({
const
isServerError
=
[
'server'
,
'edge-server'
].
includes
(
const
isServerError
=
[
'server'
,
'edge-server'
].
includes
(
getErrorSource
(
error
)
||
''
getErrorSource
(
error
)
||
''
)
)
const
isFromConsoleError
=
error
instanceof
ConsoleError
const
isUnhandledError
=
isUnhandledConsoleOrRejection
(
error
)
const
errorDetails
:
HydrationErrorState
=
(
error
as
any
).
details
||
{}
const
errorDetails
:
HydrationErrorState
=
(
error
as
any
).
details
||
{}
const
notes
=
errorDetails
.
notes
||
''
const
notes
=
errorDetails
.
notes
||
''
const
[
warningTemplate
,
serverContent
,
clientContent
]
=
const
[
warningTemplate
,
serverContent
,
clientContent
]
=
...
@@ -308,7 +307,7 @@ export function Errors({
...
@@ -308,7 +307,7 @@ export function Errors({
>
>
{
isServerError
{
isServerError
?
'Server Error'
?
'Server Error'
:
is
FromConsole
Error
:
is
Unhandled
Error
?
'Console Error'
?
'Console Error'
:
'Unhandled Runtime Error'
}
:
'Unhandled Runtime Error'
}
</
h1
>
</
h1
>
...
...
packages/next/src/client/components/react-dev-overlay/internal/helpers/console-error.ts
View file @
064970e0
export
class
ConsoleError
extends
Error
{
// Represent non Error shape unhandled promise rejections or console.error errors.
constructor
(
message
:
string
)
{
// Those errors will be captured and displayed in Error Overlay.
super
(
message
)
type
UnhandledError
=
Error
&
{
digest
:
'NEXT_UNHANDLED_ERROR'
}
this
.
name
=
'ConsoleError'
}
export
function
createUnhandledError
(
message
:
string
):
UnhandledError
{
const
error
=
new
Error
(
message
)
as
UnhandledError
error
.
digest
=
'NEXT_UNHANDLED_ERROR'
return
error
}
export
const
isUnhandledConsoleOrRejection
=
(
error
:
any
):
error
is
UnhandledError
=>
{
return
error
&&
error
.
digest
===
'NEXT_UNHANDLED_ERROR'
}
}
packages/next/src/client/components/react-dev-overlay/internal/helpers/parse-component-stack.ts
View file @
064970e0
...
@@ -72,6 +72,7 @@ export function parseComponentStack(
...
@@ -72,6 +72,7 @@ export function parseComponentStack(
):
ComponentStackFrame
[]
{
):
ComponentStackFrame
[]
{
const
componentStackFrames
:
ComponentStackFrame
[]
=
[]
const
componentStackFrames
:
ComponentStackFrame
[]
=
[]
for
(
const
line
of
componentStack
.
trim
().
split
(
'
\
n'
))
{
for
(
const
line
of
componentStack
.
trim
().
split
(
'
\
n'
))
{
// TODO: support safari stack trace
// Get component and file from the component stack line
// Get component and file from the component stack line
const
match
=
/at
([^
]
+
)(
\((
.*
)\))?
/
.
exec
(
line
)
const
match
=
/at
([^
]
+
)(
\((
.*
)\))?
/
.
exec
(
line
)
if
(
match
?.[
1
])
{
if
(
match
?.[
1
])
{
...
...
packages/next/src/client/components/react-dev-overlay/internal/helpers/stitched-error.ts
0 → 100644
View file @
064970e0
import
React
from
'react'
import
isError
from
'../../../../../lib/is-error'
const
captureOwnerStack
=
(
React
as
any
).
captureOwnerStack
||
(()
=>
''
)
const
REACT_ERROR_STACK_BOTTOM_FRAME
=
'react-stack-bottom-frame'
const
REACT_ERROR_STACK_BOTTOM_FRAME_REGEX
=
new
RegExp
(
`(at
${
REACT_ERROR_STACK_BOTTOM_FRAME
}
)|(
${
REACT_ERROR_STACK_BOTTOM_FRAME
}
\\@)`
)
export
function
getReactStitchedError
<
T
=
unknown
>
(
err
:
T
):
Error
|
T
{
if
(
!
process
.
env
.
__NEXT_REACT_OWNER_STACK
)
{
return
err
}
const
isErrorInstance
=
isError
(
err
)
const
originStack
=
isErrorInstance
?
err
.
stack
||
''
:
''
const
originMessage
=
isErrorInstance
?
err
.
message
:
''
const
stackLines
=
originStack
.
split
(
'
\
n'
)
const
indexOfSplit
=
stackLines
.
findIndex
((
line
)
=>
REACT_ERROR_STACK_BOTTOM_FRAME_REGEX
.
test
(
line
)
)
const
isOriginalReactError
=
indexOfSplit
>=
0
// has the react-stack-bottom-frame
let
newStack
=
isOriginalReactError
?
stackLines
.
slice
(
0
,
indexOfSplit
).
join
(
'
\
n'
)
:
originStack
const
newError
=
new
Error
(
originMessage
)
// Copy all enumerable properties, e.g. digest
Object
.
assign
(
newError
,
err
)
newError
.
stack
=
newStack
// Avoid duplicate overriding stack frames
const
ownerStack
=
captureOwnerStack
()
if
(
ownerStack
&&
newStack
.
endsWith
(
ownerStack
)
===
false
)
{
newStack
+=
ownerStack
// Override stack
newError
.
stack
=
newStack
}
return
newError
}
packages/next/src/client/components/react-dev-overlay/internal/helpers/use-error-handler.ts
View file @
064970e0
...
@@ -4,7 +4,7 @@ import { isNextRouterError } from '../../../is-next-router-error'
...
@@ -4,7 +4,7 @@ import { isNextRouterError } from '../../../is-next-router-error'
import
{
storeHydrationErrorStateFromConsoleArgs
}
from
'./hydration-error-info'
import
{
storeHydrationErrorStateFromConsoleArgs
}
from
'./hydration-error-info'
import
{
formatConsoleArgs
}
from
'../../../../lib/console'
import
{
formatConsoleArgs
}
from
'../../../../lib/console'
import
isError
from
'../../../../../lib/is-error'
import
isError
from
'../../../../../lib/is-error'
import
{
Console
Error
}
from
'./console-error'
import
{
createUnhandled
Error
}
from
'./console-error'
import
{
enqueueConsecutiveDedupedError
}
from
'./enqueue-client-error'
import
{
enqueueConsecutiveDedupedError
}
from
'./enqueue-client-error'
export
type
ErrorHandler
=
(
error
:
Error
)
=>
void
export
type
ErrorHandler
=
(
error
:
Error
)
=>
void
...
@@ -22,7 +22,7 @@ export function handleClientError(
...
@@ -22,7 +22,7 @@ export function handleClientError(
if
(
!
originError
||
!
isError
(
originError
))
{
if
(
!
originError
||
!
isError
(
originError
))
{
// If it's not an error, format the args into an error
// If it's not an error, format the args into an error
const
formattedErrorMessage
=
formatConsoleArgs
(
consoleErrorArgs
)
const
formattedErrorMessage
=
formatConsoleArgs
(
consoleErrorArgs
)
error
=
new
Console
Error
(
formattedErrorMessage
)
error
=
createUnhandled
Error
(
formattedErrorMessage
)
}
else
{
}
else
{
error
=
originError
error
=
originError
}
}
...
@@ -60,48 +60,40 @@ export function useErrorHandler(
...
@@ -60,48 +60,40 @@ export function useErrorHandler(
},
[
handleOnUnhandledError
,
handleOnUnhandledRejection
])
},
[
handleOnUnhandledError
,
handleOnUnhandledRejection
])
}
}
export
function
handleGlobalErrors
()
{
function
onUnhandledError
(
event
:
WindowEventMap
[
'error'
]):
void
|
boolean
{
if
(
typeof
window
!==
'undefined'
)
{
try
{
// Increase the number of stack frames on the client
Error
.
stackTraceLimit
=
50
}
catch
{}
window
.
addEventListener
(
'error'
,
(
event
:
WindowEventMap
[
'error'
]):
void
|
boolean
=>
{
if
(
isNextRouterError
(
event
.
error
))
{
if
(
isNextRouterError
(
event
.
error
))
{
event
.
preventDefault
()
event
.
preventDefault
()
return
false
return
false
}
}
handleClientError
(
event
.
error
,
[])
handleClientError
(
event
.
error
,
[])
}
}
)
window
.
addEventListener
(
function
onUnhandledRejection
(
ev
:
WindowEventMap
[
'unhandledrejection'
]):
void
{
'unhandledrejection'
,
(
ev
:
WindowEventMap
[
'unhandledrejection'
]):
void
=>
{
const
reason
=
ev
?.
reason
const
reason
=
ev
?.
reason
if
(
isNextRouterError
(
reason
))
{
if
(
isNextRouterError
(
reason
))
{
ev
.
preventDefault
()
ev
.
preventDefault
()
return
return
}
}
if
(
let
error
=
reason
!
reason
||
if
(
error
&&
!
isError
(
error
))
{
!
(
reason
instanceof
Error
)
||
error
=
createUnhandledError
(
error
+
''
)
typeof
reason
.
stack
!==
'string'
)
{
// A non-error was thrown, we don't have anything to show. :-(
return
}
}
const
e
=
reason
rejectionQueue
.
push
(
error
)
rejectionQueue
.
push
(
e
)
for
(
const
handler
of
rejectionHandlers
)
{
for
(
const
handler
of
rejectionHandlers
)
{
handler
(
e
)
handler
(
error
)
}
}
}
)
}
export
function
handleGlobalErrors
()
{
if
(
typeof
window
!==
'undefined'
)
{
try
{
// Increase the number of stack frames on the client
Error
.
stackTraceLimit
=
50
}
catch
{}
window
.
addEventListener
(
'error'
,
onUnhandledError
)
window
.
addEventListener
(
'unhandledrejection'
,
onUnhandledRejection
)
}
}
}
}
packages/next/src/client/index.tsx
View file @
064970e0
/* global location */
/* global location */
// imports polyfill from `@next/polyfill-module` after build.
// imports polyfill from `@next/polyfill-module` after build.
import
'../build/polyfills/polyfill-module'
import
'../build/polyfills/polyfill-module'
import
type
Router
from
'../shared/lib/router/router'
import
type
Router
from
'../shared/lib/router/router'
import
type
{
import
type
{
AppComponent
,
AppComponent
,
...
@@ -46,7 +45,7 @@ import {
...
@@ -46,7 +45,7 @@ import {
SearchParamsContext
,
SearchParamsContext
,
PathParamsContext
,
PathParamsContext
,
}
from
'../shared/lib/hooks-client-context.shared-runtime'
}
from
'../shared/lib/hooks-client-context.shared-runtime'
import
{
onRecoverableError
}
from
'./
on-recoverable-error
'
import
{
onRecoverableError
}
from
'./
react-client-callbacks/shared
'
import
tracer
from
'./tracing/tracer'
import
tracer
from
'./tracing/tracer'
import
reportToSocket
from
'./tracing/report-to-socket'
import
reportToSocket
from
'./tracing/report-to-socket'
...
...
packages/next/src/client/on-recoverable-error.ts
deleted
100644 → 0
View file @
6fba7b24
import
{
isBailoutToCSRError
}
from
'../shared/lib/lazy-dynamic/bailout-to-csr'
// x-ref: https://github.com/facebook/react/blob/d4bc16a7d69eb2ea38a88c8ac0b461d5f72cdcab/packages/react-dom/src/client/ReactDOMRoot.js#L83
const
defaultOnRecoverableError
=
typeof
reportError
===
'function'
?
// In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError
:
(
error
:
any
)
=>
{
window
.
console
.
error
(
error
)
}
export
function
onRecoverableError
(
err
:
unknown
,
errorInfo
:
{
componentStack
?:
string
}
)
{
// In development mode, pass along the component stack to the error
if
(
process
.
env
.
NODE_ENV
===
'development'
&&
errorInfo
.
componentStack
)
{
;(
err
as
any
).
_componentStack
=
errorInfo
.
componentStack
}
// Using default react onRecoverableError
// Skip certain custom errors which are not expected to be reported on client
if
(
isBailoutToCSRError
(
err
))
return
defaultOnRecoverableError
(
err
)
}
packages/next/src/client/react-client-callbacks/app-router.ts
0 → 100644
View file @
064970e0
// This file is only used in app router due to the specific error state handling.
import
type
{
HydrationOptions
}
from
'react-dom/client'
import
{
getReactStitchedError
}
from
'../components/react-dev-overlay/internal/helpers/stitched-error'
import
{
handleClientError
}
from
'../components/react-dev-overlay/internal/helpers/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
isError
from
'../../lib/is-error'
import
{
originConsoleError
}
from
'../components/globals/intercept-console-error'
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
const
stitchedError
=
getReactStitchedError
(
err
)
if
(
process
.
env
.
NODE_ENV
===
'development'
)
{
const
errorBoundaryComponent
=
errorInfo
?.
errorBoundary
?.
constructor
const
errorBoundaryName
=
// read react component displayName
(
errorBoundaryComponent
as
any
)?.
displayName
||
errorBoundaryComponent
?.
name
||
'Unknown'
const
componentThatErroredFrame
=
errorInfo
?.
componentStack
?.
split
(
'
\
n'
)[
1
]
// Match chrome or safari stack trace
const
matches
=
// regex to match the function name in the stack trace
// example 1: at Page (http://localhost:3000/_next/static/chunks/pages/index.js?ts=1631600000000:2:1)
// example 2: Page@http://localhost:3000/_next/static/chunks/pages/index.js?ts=1631600000000:2:1
componentThatErroredFrame
?.
match
(
/
\s
+at
(\w
+
)\s
+|
(\w
+
)
@/
)
??
[]
const
componentThatErroredName
=
matches
[
1
]
||
matches
[
2
]
||
'Unknown'
// In development mode, pass along the component stack to the error
if
(
process
.
env
.
NODE_ENV
===
'development'
&&
errorInfo
.
componentStack
)
{
;(
stitchedError
as
any
).
_componentStack
=
errorInfo
.
componentStack
}
// Create error location with errored component and error boundary, to match the behavior of default React onCaughtError handler.
const
errorBoundaryMessage
=
`It was handled by the <
${
errorBoundaryName
}
> error boundary.`
const
componentErrorMessage
=
componentThatErroredName
?
`The above error occurred in the <
${
componentThatErroredName
}
> component.`
:
`The above error occurred in one of your components.`
const
errorLocation
=
`
${
componentErrorMessage
}
${
errorBoundaryMessage
}
`
const
originErrorStack
=
isError
(
err
)
?
err
.
stack
||
''
:
''
// Log the modified error message with stack so without being intercepted again.
originConsoleError
(
originErrorStack
+
'
\
n
\
n'
+
errorLocation
)
handleClientError
(
stitchedError
,
[])
}
else
{
originConsoleError
(
err
)
}
}
export
const
onUncaughtError
:
HydrationOptions
[
'onUncaughtError'
]
=
(
err
,
errorInfo
)
=>
{
// Skip certain custom errors which are not expected to be reported on client
if
(
isBailoutToCSRError
(
err
)
||
isNextRouterError
(
err
))
return
const
stitchedError
=
getReactStitchedError
(
err
)
if
(
process
.
env
.
NODE_ENV
===
'development'
)
{
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'
// In development mode, pass along the component stack to the error
if
(
process
.
env
.
NODE_ENV
===
'development'
&&
errorInfo
.
componentStack
)
{
;(
stitchedError
as
any
).
_componentStack
=
errorInfo
.
componentStack
}
// 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
errStack
=
(
stitchedError
as
any
).
stack
||
''
// Log the modified error message with stack so without being intercepted again.
originConsoleError
(
errStack
+
'
\
n
\
n'
+
errorLocation
)
reportGlobalError
(
stitchedError
)
}
else
{
reportGlobalError
(
err
)
}
}
packages/next/src/client/react-client-callbacks/report-global-error.ts
0 → 100644
View file @
064970e0
export
const
reportGlobalError
=
typeof
reportError
===
'function'
?
// In modern browsers, reportError will dispatch an error event,
// emulating an uncaught JavaScript error.
reportError
:
(
error
:
unknown
)
=>
{
window
.
console
.
error
(
error
)
}
packages/next/src/client/react-client-callbacks/shared.ts
0 → 100644
View file @
064970e0
// This module can be shared between both pages router and app router
import
type
{
HydrationOptions
}
from
'react-dom/client'
import
{
isBailoutToCSRError
}
from
'../../shared/lib/lazy-dynamic/bailout-to-csr'
import
{
reportGlobalError
}
from
'./report-global-error'
import
{
getReactStitchedError
}
from
'../components/react-dev-overlay/internal/helpers/stitched-error'
export
const
onRecoverableError
:
HydrationOptions
[
'onRecoverableError'
]
=
(
err
,
errorInfo
)
=>
{
const
stitchedError
=
getReactStitchedError
(
err
)
// In development mode, pass along the component stack to the error
if
(
process
.
env
.
NODE_ENV
===
'development'
&&
errorInfo
.
componentStack
)
{
;(
stitchedError
as
any
).
_componentStack
=
errorInfo
.
componentStack
}
// Skip certain custom errors which are not expected to be reported on client
if
(
isBailoutToCSRError
(
err
))
return
reportGlobalError
(
stitchedError
)
}
packages/next/src/lib/needs-experimental-react.ts
View file @
064970e0
import
type
{
NextConfig
}
from
'../server/config-shared'
import
type
{
NextConfig
}
from
'../server/config-shared'
export
function
needsExperimentalReact
(
config
:
NextConfig
)
{
export
function
needsExperimentalReact
(
config
:
NextConfig
)
{
return
Boolean
(
config
.
experimental
?.
ppr
||
config
.
experimental
?.
taint
)
const
{
ppr
,
taint
,
reactOwnerStack
}
=
config
.
experimental
||
{}
return
Boolean
(
ppr
||
taint
||
reactOwnerStack
)
}
}
packages/next/src/server/config-schema.ts
View file @
064970e0
...
@@ -333,6 +333,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
...
@@ -333,6 +333,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.
readonly
()
.
readonly
()
.
optional
(),
.
optional
(),
taint
:
z
.
boolean
().
optional
(),
taint
:
z
.
boolean
().
optional
(),
reactOwnerStack
:
z
.
boolean
().
optional
(),
prerenderEarlyExit
:
z
.
boolean
().
optional
(),
prerenderEarlyExit
:
z
.
boolean
().
optional
(),
proxyTimeout
:
z
.
number
().
gte
(
0
).
optional
(),
proxyTimeout
:
z
.
number
().
gte
(
0
).
optional
(),
scrollRestoration
:
z
.
boolean
().
optional
(),
scrollRestoration
:
z
.
boolean
().
optional
(),
...
...
packages/next/src/server/config-shared.ts
View file @
064970e0
...
@@ -462,6 +462,12 @@ export interface ExperimentalConfig {
...
@@ -462,6 +462,12 @@ export interface ExperimentalConfig {
*/
*/
taint
?:
boolean
taint
?:
boolean
/**
* Enables leveraging experimental captureOwnerStack API in React,
* to create a better stack trace for React errors.
*/
reactOwnerStack
?:
boolean
serverActions
?:
{
serverActions
?:
{
/**
/**
* Allows adjusting body parser size limit for server actions.
* Allows adjusting body parser size limit for server actions.
...
@@ -1141,6 +1147,7 @@ export const defaultConfig: NextConfig = {
...
@@ -1141,6 +1147,7 @@ export const defaultConfig: NextConfig = {
process
.
env
.
__NEXT_TEST_MODE
&&
process
.
env
.
__NEXT_TEST_MODE
&&
process
.
env
.
__NEXT_EXPERIMENTAL_PPR
===
'true'
process
.
env
.
__NEXT_EXPERIMENTAL_PPR
===
'true'
),
),
reactOwnerStack
:
false
,
webpackBuildWorker
:
undefined
,
webpackBuildWorker
:
undefined
,
webpackMemoryOptimizations
:
false
,
webpackMemoryOptimizations
:
false
,
optimizeServerReact
:
true
,
optimizeServerReact
:
true
,
...
...
test/development/acceptance-app/ReactRefreshLogBox.test.ts
View file @
064970e0
...
@@ -4,7 +4,6 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
...
@@ -4,7 +4,6 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import
{
import
{
check
,
check
,
describeVariants
as
describe
,
describeVariants
as
describe
,
expandCallStack
,
getRedboxCallStackCollapsed
,
getRedboxCallStackCollapsed
,
retry
,
retry
,
}
from
'next-test-utils'
}
from
'next-test-utils'
...
@@ -777,7 +776,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
...
@@ -777,7 +776,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
await
cleanup
()
await
cleanup
()
})
})
test
(
'Call stack
count
for client error'
,
async
()
=>
{
test
(
'Call stack for client error'
,
async
()
=>
{
const
{
session
,
browser
,
cleanup
}
=
await
sandbox
(
const
{
session
,
browser
,
cleanup
}
=
await
sandbox
(
next
,
next
,
new
Map
([
new
Map
([
...
@@ -796,25 +795,30 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
...
@@ -796,25 +795,30 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
])
])
)
)
try
{
await
session
.
assertHasRedbox
()
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Should still show the errored line in source code
const
source
=
await
session
.
getRedboxSource
()
expect
(
source
).
toContain
(
'app/page.js'
)
expect
(
source
).
toContain
(
`throw new Error('Client error')`
)
// Expect more than the default amount of frames
await
expect
(
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
browser
.
hasElementByCssSelector
(
const
callStackFrames
=
await
browser
.
elementsByCss
(
'[data-nextjs-data-runtime-error-collapsed-action]'
'[data-nextjs-call-stack-frame]'
)
)
).
resolves
.
toEqual
(
false
)
expect
(
callStackFrames
.
length
).
toBeGreaterThan
(
9
)
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
const
moduleGroup
=
await
browser
.
elementsByCss
(
'[data-nextjs-collapsed-call-stack-details]'
)
)
// Expect some of the call stack frames to be grouped (by React or Next.js)
const
stackFrames
=
(
expect
(
moduleGroup
.
length
).
toBeGreaterThan
(
0
)
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
()))
).
filter
(
Boolean
)
expect
(
stackFrames
).
toEqual
([])
}
finally
{
await
cleanup
()
await
cleanup
()
}
})
})
test
(
'Call stack for server error'
,
async
()
=>
{
test
(
'Call stack for server error'
,
async
()
=>
{
...
@@ -849,20 +853,10 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
...
@@ -849,20 +853,10 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
const
stackFrameElements
=
await
browser
.
elementsByCss
(
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
'[data-nextjs-call-stack-frame]'
)
)
const
stackFrames
=
await
Promise
.
all
(
const
stackFrames
=
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
()))
)
).
filter
(
Boolean
)
expect
(
stackFrames
).
toEqual
(
expect
(
stackFrames
).
toEqual
([])
// TODO: Show useful stack
[
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
''
,
''
,
''
,
''
,
]
)
}
finally
{
}
finally
{
await
cleanup
()
await
cleanup
()
}
}
...
...
test/development/acceptance/ReactRefreshLogBox.test.ts
View file @
064970e0
/* eslint-env jest */
/* eslint-env jest */
import
{
sandbox
}
from
'development-sandbox'
import
{
sandbox
}
from
'development-sandbox'
import
{
FileRef
,
nextTestSetup
}
from
'e2e-utils'
import
{
FileRef
,
nextTestSetup
}
from
'e2e-utils'
import
{
describeVariants
as
describe
,
expandCallStack
}
from
'next-test-utils'
import
{
describeVariants
as
describe
}
from
'next-test-utils'
import
path
from
'path'
import
path
from
'path'
import
{
outdent
}
from
'outdent'
import
{
outdent
}
from
'outdent'
...
@@ -765,8 +765,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
...
@@ -765,8 +765,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
await
session
.
assertHasRedbox
()
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Expect more than the default amount of frames
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const
callStackFrames
=
await
browser
.
elementsByCss
(
const
callStackFrames
=
await
browser
.
elementsByCss
(
...
@@ -805,7 +803,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
...
@@ -805,7 +803,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
])
)
)
await
session
.
assertHasRedbox
()
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
let
callStackFrames
=
await
browser
.
elementsByCss
(
let
callStackFrames
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
'[data-nextjs-call-stack-frame]'
)
)
...
@@ -835,7 +832,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
...
@@ -835,7 +832,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
])
)
)
await
session
.
assertHasRedbox
()
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Should still show the errored line in source code
// Should still show the errored line in source code
const
source
=
await
session
.
getRedboxSource
()
const
source
=
await
session
.
getRedboxSource
()
...
...
test/development/app-dir/dynamic-error-trace/index.test.ts
View file @
064970e0
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
import
{
assertHasRedbox
,
getRedboxSource
}
from
'next-test-utils'
assertHasRedbox
,
shouldRunTurboDevTest
,
getRedboxSource
,
}
from
'next-test-utils'
import
{
outdent
}
from
'outdent'
import
{
outdent
}
from
'outdent'
const
isReactExperimental
=
process
.
env
.
__NEXT_EXPERIMENTAL_PPR
===
'true'
function
normalizeStackTrace
(
trace
)
{
return
trace
.
replace
(
/
\(
.*
\)
/g
,
''
)
}
describe
(
'app dir - dynamic error trace'
,
()
=>
{
describe
(
'app dir - dynamic error trace'
,
()
=>
{
const
{
next
,
skipped
}
=
nextTestSetup
({
const
{
next
,
skipped
}
=
nextTestSetup
({
files
:
__dirname
,
files
:
__dirname
,
dependencies
:
{
swr
:
'latest'
,
},
packageJson
:
{
scripts
:
{
build
:
'next build'
,
dev
:
`next
${
shouldRunTurboDevTest
()
?
'dev --turbo'
:
'dev'
}
`
,
start
:
'next start'
,
},
},
installCommand
:
'pnpm install'
,
startCommand
:
(
global
as
any
).
isNextDev
?
'pnpm dev'
:
'pnpm start'
,
buildCommand
:
'pnpm build'
,
skipDeployment
:
true
,
skipDeployment
:
true
,
})
})
if
(
skipped
)
return
if
(
skipped
)
return
...
@@ -40,20 +29,15 @@ describe('app dir - dynamic error trace', () => {
...
@@ -40,20 +29,15 @@ describe('app dir - dynamic error trace', () => {
const
stackFrameElements
=
await
browser
.
elementsByCss
(
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
'[data-nextjs-call-stack-frame]'
)
)
const
stackFrames
=
await
Promise
.
all
(
const
stackFramesContent
=
// TODO: Why is this text empty?
// TODO: Why is this text empty?
(
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())))
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())
// Filter out the frames having code snippet but without methodName and source
)
.
filter
(
Boolean
)
expect
(
stackFrames
).
toEqual
(
.
join
(
'
\
n'
)
// TODO: Show useful stack
// TODO: Show useful stack
[
expect
(
normalizeStackTrace
(
stackFramesContent
)).
toMatchInlineSnapshot
(
// Internal frames of React.
isReactExperimental
?
`""`
:
`""`
// Feel free to adjust until we show useful stacks.
''
,
''
,
''
,
''
,
]
)
)
const
codeframe
=
await
getRedboxSource
(
browser
)
const
codeframe
=
await
getRedboxSource
(
browser
)
...
...
test/development/app-dir/owner-stack/app/browser/caught/page.js
0 → 100644
View file @
064970e0
'use client'
import
{
Component
}
from
'react'
class
MyErrorBoundary
extends
Component
{
static
getDerivedStateFromError
(
error
)
{
return
{
error
}
}
state
=
{
error
:
null
}
render
()
{
if
(
this
.
state
.
error
)
{
return
'failed'
}
return
this
.
props
.
children
}
}
function
Inner
()
{
return
(
<
MyErrorBoundary
>
<
Thrower
/>
<
/MyErrorBoundary
>
)
}
function
Thrower
()
{
useErrorHook
()
}
function
useThrowError
()
{
if
(
typeof
window
!==
'undefined'
)
{
throw
new
Error
(
'browser error'
)
}
}
function
useErrorHook
()
{
useThrowError
()
}
export
default
function
Page
()
{
return
<
Inner
/>
}
test/development/app-dir/owner-stack/app/browser/reject-promise/page.js
0 → 100644
View file @
064970e0
'use client'
function
useThrowError
()
{
if
(
typeof
window
!==
'undefined'
)
{
Promise
.
reject
(
'string in rejected promise'
)
}
}
function
useErrorHook
()
{
useThrowError
()
}
export
default
function
Page
()
{
useErrorHook
()
return
<
p
>
hello
world
<
/p
>
}
test/development/app-dir/owner-stack/app/browser/uncaught/page.js
0 → 100644
View file @
064970e0
'use client'
function
useThrowError
()
{
if
(
typeof
window
!==
'undefined'
)
{
throw
new
Error
(
'browser error'
)
}
}
function
useErrorHook
()
{
useThrowError
()
}
export
default
function
Page
()
{
useErrorHook
()
return
<
p
>
hello
world
<
/p
>
}
test/development/app-dir/owner-stack/app/layout.js
0 → 100644
View file @
064970e0
export
default
function
Root
({
children
})
{
return
(
<
html
>
<
body
>
{
children
}
<
/body
>
<
/html
>
)
}
test/development/app-dir/owner-stack/app/ssr/page.js
0 → 100644
View file @
064970e0
'use client'
function
useThrowError
()
{
throw
new
Error
(
'ssr error'
)
}
function
useErrorHook
()
{
useThrowError
()
}
export
default
function
Page
()
{
useErrorHook
()
return
<
p
>
hello
world
<
/p
>
}
test/development/app-dir/owner-stack/next.config.js
0 → 100644
View file @
064970e0
/**
* @type {import('next').NextConfig}
*/
const
nextConfig
=
{
experimental
:
{
reactOwnerStack
:
true
,
},
}
module
.
exports
=
nextConfig
test/development/app-dir/owner-stack/owner-stack.test.ts
0 → 100644
View file @
064970e0
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
assertHasRedbox
,
assertNoRedbox
,
waitForAndOpenRuntimeError
,
getRedboxDescription
,
}
from
'next-test-utils'
// TODO: parse the location and assert them in the future
// Remove the location `()` part in every line of stack trace;
// Remove the leading spaces in every line of stack trace;
// Remove the trailing spaces in every line of stack trace;
function
normalizeStackTrace
(
trace
:
string
)
{
return
trace
.
replace
(
/
\(
.*
\)
/g
,
''
)
.
replace
(
/^
\s
+/gm
,
''
)
.
trim
()
}
async
function
getStackFramesContent
(
browser
)
{
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
const
stackFramesContent
=
(
await
Promise
.
all
(
stackFrameElements
.
map
(
async
(
frame
)
=>
{
const
functionNameEl
=
await
frame
.
$
(
'[data-nextjs-frame-expanded]'
)
const
sourceEl
=
await
frame
.
$
(
'[data-has-source]'
)
const
functionName
=
functionNameEl
?
await
functionNameEl
.
innerText
()
:
''
const
source
=
sourceEl
?
await
sourceEl
.
innerText
()
:
''
if
(
!
functionName
)
{
return
''
}
return
`at
${
functionName
}
(
${
source
}
)`
})
)
)
.
filter
(
Boolean
)
.
join
(
'
\
n'
)
return
stackFramesContent
}
describe
(
'app-dir - owner-stack'
,
()
=>
{
const
{
next
}
=
nextTestSetup
({
files
:
__dirname
,
})
it
(
'should log stitched error for browser uncaught errors'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/browser/uncaught'
)
await
assertHasRedbox
(
browser
)
const
stackFramesContent
=
await
getStackFramesContent
(
browser
)
if
(
process
.
env
.
TURBOPACK
)
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useErrorHook (app/browser/uncaught/page.js (10:3))
at Page (app/browser/uncaught/page.js (14:3))"
`
)
}
else
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useThrowError (app/browser/uncaught/page.js (10:3))
at useErrorHook (app/browser/uncaught/page.js (14:3))"
`
)
}
const
logs
=
await
browser
.
log
()
const
errorLog
=
logs
.
find
((
log
)
=>
{
return
log
.
message
.
includes
(
'Error: browser error'
)
}).
message
if
(
process
.
env
.
TURBOPACK
)
{
expect
(
normalizeStackTrace
(
errorLog
)).
toMatchInlineSnapshot
(
`
"Error: browser error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`
)
}
else
{
expect
(
normalizeStackTrace
(
errorLog
)).
toMatchInlineSnapshot
(
`
"Error: browser error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`
)
}
})
it
(
'should log stitched error for browser caught errors'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/browser/caught'
)
await
assertNoRedbox
(
browser
)
const
logs
=
await
browser
.
log
()
const
errorLog
=
logs
.
find
((
log
)
=>
{
return
log
.
message
.
includes
(
'Error: browser error'
)
}).
message
await
waitForAndOpenRuntimeError
(
browser
)
const
stackFramesContent
=
await
getStackFramesContent
(
browser
)
if
(
process
.
env
.
TURBOPACK
)
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useErrorHook (app/browser/caught/page.js (39:3))
at Thrower (app/browser/caught/page.js (29:3))
at Inner (app/browser/caught/page.js (23:7))
at Page (app/browser/caught/page.js (43:10))"
`
)
}
else
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useThrowError (app/browser/caught/page.js (39:3))
at useErrorHook (app/browser/caught/page.js (29:3))
at Thrower (app/browser/caught/page.js (23:8))
at Inner (app/browser/caught/page.js (43:11))"
`
)
}
expect
(
normalizeStackTrace
(
errorLog
)).
toMatchInlineSnapshot
(
`
"Error: browser error
at useThrowError
at useErrorHook
at Thrower
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Thrower> component. It was handled by the <MyErrorBoundary> error boundary."
`
)
})
it
(
'should log stitched error for SSR errors'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/ssr'
)
await
assertHasRedbox
(
browser
)
const
stackFramesContent
=
await
getStackFramesContent
(
browser
)
if
(
process
.
env
.
TURBOPACK
)
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useErrorHook (app/ssr/page.js (8:3))
at Page (app/ssr/page.js (12:3))"
`
)
}
else
{
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`
"at useThrowError (app/ssr/page.js (8:3))
at useErrorHook (app/ssr/page.js (12:3))"
`
)
}
const
logs
=
await
browser
.
log
()
const
errorLog
=
logs
.
find
((
log
)
=>
{
return
log
.
message
.
includes
(
'Error: ssr error'
)
}).
message
expect
(
normalizeStackTrace
(
errorLog
)).
toMatchInlineSnapshot
(
`
"Error: ssr error
at useThrowError
at useErrorHook
at Page
at react-stack-bottom-frame
at renderWithHooks
at updateFunctionComponent
at beginWork
at runWithFiberInDEV
at performUnitOfWork
at workLoopSync
at renderRootSync
at performWorkOnRoot
at performWorkOnRootViaSchedulerTask
at MessagePort.performWorkUntilDeadline
The above error occurred in the <Page> component. It was handled by the <ReactDevOverlay> error boundary."
`
)
})
it
(
'should capture unhandled promise rejections'
,
async
()
=>
{
const
browser
=
await
next
.
browser
(
'/browser/reject-promise'
)
await
waitForAndOpenRuntimeError
(
browser
)
await
assertHasRedbox
(
browser
)
const
description
=
await
getRedboxDescription
(
browser
)
expect
(
description
).
toMatchInlineSnapshot
(
`"string in rejected promise"`
)
// Promise rejection has no owner stack
const
stackFramesContent
=
await
getStackFramesContent
(
browser
)
expect
(
stackFramesContent
).
toMatchInlineSnapshot
(
`""`
)
})
})
test/lib/next-test-utils.ts
View file @
064970e0
...
@@ -1253,15 +1253,6 @@ export async function toggleCollapseComponentStack(
...
@@ -1253,15 +1253,6 @@ export async function toggleCollapseComponentStack(
.
click
()
.
click
()
}
}
export
async
function
expandCallStack
(
browser
:
BrowserInterface
):
Promise
<
void
>
{
// Open full Call Stack
await
browser
.
elementByCss
(
'[data-nextjs-data-runtime-error-collapsed-action]'
)
.
click
()
}
export
async
function
getRedboxCallStack
(
export
async
function
getRedboxCallStack
(
browser
:
BrowserInterface
browser
:
BrowserInterface
):
Promise
<
string
>
{
):
Promise
<
string
>
{
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment