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
Hide 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 {
/// directory.
ppr
:
Option
<
ExperimentalPartialPrerendering
>
,
taint
:
Option
<
bool
>
,
react_owner_stack
:
Option
<
bool
>
,
#[serde(rename
=
"dynamicIO"
)]
dynamic_io
:
Option
<
bool
>
,
proxy_timeout
:
Option
<
f64
>
,
...
...
@@ -1148,6 +1149,13 @@ impl NextConfig {
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]
pub
fn
use_swc_css
(
&
self
)
->
Vc
<
bool
>
{
Vc
::
cell
(
...
...
crates/next-core/src/next_import_map.rs
View file @
064970e0
...
...
@@ -116,12 +116,14 @@ pub async fn get_next_client_import_map(
match
ty
.into_value
()
{
ClientContextType
::
Pages
{
..
}
=>
{}
ClientContextType
::
App
{
app_dir
}
=>
{
let
react_flavor
=
if
*
next_config
.enable_ppr
()
.await
?
||
*
next_config
.enable_taint
()
.await
?
{
"-experimental"
}
else
{
""
};
let
react_flavor
=
if
*
next_config
.enable_ppr
()
.await
?
||
*
next_config
.enable_taint
()
.await
?
||
*
next_config
.enable_react_owner_stack
()
.await
?
{
"-experimental"
}
else
{
""
};
import_map
.insert_exact_alias
(
"react"
,
...
...
@@ -683,7 +685,12 @@ async fn rsc_aliases(
)
->
Result
<
()
>
{
let
ppr
=
*
next_config
.enable_ppr
()
.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
mut
alias
=
FxIndexMap
::
default
();
...
...
packages/next/src/build/webpack/plugins/define-env-plugin.ts
View file @
064970e0
...
...
@@ -185,6 +185,9 @@ export function getDefineEnv({
),
'process.env.__NEXT_PPR'
:
checkIsAppPPREnabled
(
config
.
experimental
.
ppr
),
'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_DEPLOYMENT_ID'
:
config
.
deploymentId
||
false
,
'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'
// eslint-disable-next-line import/no-extraneous-dependencies
import
{
createFromReadableStream
}
from
'react-server-dom-webpack/client'
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
{
findSourceMapURL
}
from
'./app-find-source-map-url'
import
{
...
...
@@ -23,6 +27,8 @@ import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runt
/// <reference types="react-dom/experimental" />
const
isReactOwnerStackEnabled
=
!!
process
.
env
.
__NEXT_REACT_OWNER_STACK
const
appElement
:
HTMLElement
|
Document
|
null
=
document
const
encoder
=
new
TextEncoder
()
...
...
@@ -227,8 +233,17 @@ export function hydrate() {
const
rootLayoutMissingTags
=
window
.
__next_root_layout_missing_tags
const
hasMissingTags
=
!!
rootLayoutMissingTags
?.
length
const
errorCallbacks
=
isReactOwnerStackEnabled
&&
process
.
env
.
NODE_ENV
!==
'production'
?
{
onCaughtError
,
onUncaughtError
,
}
:
undefined
const
options
=
{
onRecoverableError
,
...
errorCallbacks
,
}
satisfies
ReactDOMClient
.
RootOptions
const
isError
=
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'
import
{
isNextRouterError
}
from
'../is-next-router-error'
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
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
{
ShadowPortal
}
from
'../internal/components/ShadowPortal'
import
{
BuildError
}
from
'../internal/container/BuildError'
import
{
Errors
}
from
'../internal/container/Errors'
import
{
StaticIndicator
}
from
'../internal/container/StaticIndicator'
import
type
{
SupportedErrorEvent
}
from
'../internal/container/Errors'
import
{
Errors
,
type
SupportedErrorEvent
}
from
'../internal/container/Errors'
import
{
parseStack
}
from
'../internal/helpers/parse-stack'
import
{
StaticIndicator
}
from
'../internal/container/StaticIndicator'
import
{
Base
}
from
'../internal/styles/Base'
import
{
ComponentStyles
}
from
'../internal/styles/ComponentStyles'
import
{
CssReset
}
from
'../internal/styles/CssReset'
import
{
RootLayoutMissingTagsError
}
from
'../internal/container/root-layout-missing-tags-error'
import
type
{
Dispatcher
}
from
'./hot-reloader-client'
import
{
RuntimeErrorHandler
}
from
'../internal/helpers/runtime-error-handler'
interface
ReactDevOverlayState
{
reactError
:
SupportedErrorEvent
|
null
...
...
@@ -21,7 +20,6 @@ export default class ReactDevOverlay extends React.PureComponent<
state
:
OverlayState
dispatcher
?:
Dispatcher
children
:
React
.
ReactNode
onReactError
:
(
error
:
Error
)
=>
void
},
ReactDevOverlayState
>
{
...
...
@@ -29,6 +27,8 @@ export default class ReactDevOverlay extends React.PureComponent<
static
getDerivedStateFromError
(
error
:
Error
):
ReactDevOverlayState
{
if
(
!
error
.
stack
)
return
{
reactError
:
null
}
RuntimeErrorHandler
.
hadRuntimeError
=
true
return
{
reactError
:
{
id
:
0
,
...
...
@@ -41,10 +41,6 @@ export default class ReactDevOverlay extends React.PureComponent<
}
}
componentDidCatch
(
componentErr
:
Error
)
{
this
.
props
.
onReactError
(
componentErr
)
}
render
()
{
const
{
state
,
children
,
dispatcher
}
=
this
.
props
const
{
reactError
}
=
this
.
state
...
...
@@ -79,20 +75,11 @@ export default class ReactDevOverlay extends React.PureComponent<
/>
)
:
(
<>
{
reactError
?
(
<
Errors
isAppDir=
{
true
}
versionInfo=
{
state
.
versionInfo
}
initialDisplayState=
"fullscreen"
errors=
{
[
reactError
]
}
hasStaticIndicator=
{
hasStaticIndicator
}
debugInfo=
{
debugInfo
}
/>
)
:
hasRuntimeErrors
?
(
{
hasRuntimeErrors
?
(
<
Errors
isAppDir=
{
true
}
initialDisplayState=
"minimized"
errors=
{
state
.
errors
}
initialDisplayState=
{
reactError
?
'fullscreen'
:
'minimized'
}
errors=
{
reactError
?
[
reactError
]
:
state
.
errors
}
versionInfo=
{
state
.
versionInfo
}
hasStaticIndicator=
{
hasStaticIndicator
}
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'
import
type
{
HydrationErrorState
}
from
'../internal/helpers/hydration-error-info'
import
type
{
DebugInfo
}
from
'../types'
import
{
useUntrackedPathname
}
from
'../../navigation-untracked'
import
{
getReactStitchedError
}
from
'../internal/helpers/stitched-error'
export
interface
Dispatcher
{
onBuildOk
():
void
...
...
@@ -563,10 +564,12 @@ export default function HotReload({
const
componentStackTrace
=
(
error
as
any
).
_componentStack
||
errorDetails
?.
componentStack
const
warning
=
errorDetails
?.
warning
const
stitchedError
=
getReactStitchedError
(
error
)
dispatch
({
type
:
ACTION_UNHANDLED_ERROR
,
reason
:
e
rror
,
frames
:
parseStack
(
error
.
stack
),
reason
:
stitchedE
rror
,
frames
:
parseStack
(
stitchedError
.
stack
||
''
),
componentStackFrames
:
typeof
componentStackTrace
===
'string'
?
parseComponentStack
(
componentStackTrace
)
...
...
@@ -576,19 +579,18 @@ export default function HotReload({
},
[
dispatch
]
)
const
handleOnUnhandledRejection
=
useCallback
(
(
reason
:
Error
):
void
=>
{
const
stitchedError
=
getReactStitchedError
(
reason
)
dispatch
({
type
:
ACTION_UNHANDLED_REJECTION
,
reason
:
reason
,
frames
:
parseStack
(
reason
.
stack
!
),
reason
:
stitchedError
,
frames
:
parseStack
(
stitchedError
.
stack
||
''
),
})
},
[
dispatch
]
)
const
handleOnReactError
=
useCallback
(()
=>
{
RuntimeErrorHandler
.
hadRuntimeError
=
true
},
[])
useErrorHandler
(
handleOnUnhandledError
,
handleOnUnhandledRejection
)
const
webSocketRef
=
useWebsocket
(
assetPrefix
)
...
...
@@ -674,11 +676,7 @@ export default function HotReload({
])
return
(
<
ReactDevOverlay
onReactError=
{
handleOnReactError
}
state=
{
state
}
dispatcher=
{
dispatcher
}
>
<
ReactDevOverlay
state=
{
state
}
dispatcher=
{
dispatcher
}
>
{
children
}
</
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) {
<
FallbackLayout
>
<
ReactDevOverlay
state=
{
{
...
INITIAL_OVERLAY_STATE
,
rootLayoutMissingTags
}
}
onReactError=
{
()
=>
{}
}
>
{
reactEl
}
</
ReactDevOverlay
>
...
...
packages/next/src/client/components/react-dev-overlay/internal/container/Errors.tsx
View file @
064970e0
...
...
@@ -31,7 +31,7 @@ import {
}
from
'../helpers/hydration-error-info'
import
{
NodejsInspectorCopyButton
}
from
'../components/nodejs-inspector'
import
{
CopyButton
}
from
'../components/copy-button'
import
{
ConsoleError
}
from
'../helpers/console-error'
import
{
isUnhandledConsoleOrRejection
}
from
'../helpers/console-error'
export
type
SupportedErrorEvent
=
{
id
:
number
...
...
@@ -61,11 +61,11 @@ function ErrorDescription({
error
:
Error
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
return
(
<>
{
is
FromConsole
Error
||
hydrationWarning
?
''
:
error
.
name
+
': '
}
{
is
Unhandled
Error
||
hydrationWarning
?
''
:
error
.
name
+
': '
}
<
HotlinkedText
text=
{
hydrationWarning
||
error
.
message
}
matcher=
{
isNextjsLink
}
...
...
@@ -257,8 +257,7 @@ export function Errors({
const
isServerError
=
[
'server'
,
'edge-server'
].
includes
(
getErrorSource
(
error
)
||
''
)
const
isFromConsoleError
=
error
instanceof
ConsoleError
const
isUnhandledError
=
isUnhandledConsoleOrRejection
(
error
)
const
errorDetails
:
HydrationErrorState
=
(
error
as
any
).
details
||
{}
const
notes
=
errorDetails
.
notes
||
''
const
[
warningTemplate
,
serverContent
,
clientContent
]
=
...
...
@@ -308,7 +307,7 @@ export function Errors({
>
{
isServerError
?
'Server Error'
:
is
FromConsole
Error
:
is
Unhandled
Error
?
'Console Error'
:
'Unhandled Runtime Error'
}
</
h1
>
...
...
packages/next/src/client/components/react-dev-overlay/internal/helpers/console-error.ts
View file @
064970e0
export
class
ConsoleError
extends
Error
{
constructor
(
message
:
string
)
{
super
(
message
)
this
.
name
=
'ConsoleError'
}
// Represent non Error shape unhandled promise rejections or console.error errors.
// Those errors will be captured and displayed in Error Overlay.
type
UnhandledError
=
Error
&
{
digest
:
'NEXT_UNHANDLED_ERROR'
}
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(
):
ComponentStackFrame
[]
{
const
componentStackFrames
:
ComponentStackFrame
[]
=
[]
for
(
const
line
of
componentStack
.
trim
().
split
(
'
\
n'
))
{
// TODO: support safari stack trace
// Get component and file from the component stack line
const
match
=
/at
([^
]
+
)(
\((
.*
)\))?
/
.
exec
(
line
)
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'
import
{
storeHydrationErrorStateFromConsoleArgs
}
from
'./hydration-error-info'
import
{
formatConsoleArgs
}
from
'../../../../lib/console'
import
isError
from
'../../../../../lib/is-error'
import
{
Console
Error
}
from
'./console-error'
import
{
createUnhandled
Error
}
from
'./console-error'
import
{
enqueueConsecutiveDedupedError
}
from
'./enqueue-client-error'
export
type
ErrorHandler
=
(
error
:
Error
)
=>
void
...
...
@@ -22,7 +22,7 @@ export function handleClientError(
if
(
!
originError
||
!
isError
(
originError
))
{
// If it's not an error, format the args into an error
const
formattedErrorMessage
=
formatConsoleArgs
(
consoleErrorArgs
)
error
=
new
Console
Error
(
formattedErrorMessage
)
error
=
createUnhandled
Error
(
formattedErrorMessage
)
}
else
{
error
=
originError
}
...
...
@@ -60,6 +60,32 @@ export function useErrorHandler(
},
[
handleOnUnhandledError
,
handleOnUnhandledRejection
])
}
function
onUnhandledError
(
event
:
WindowEventMap
[
'error'
]):
void
|
boolean
{
if
(
isNextRouterError
(
event
.
error
))
{
event
.
preventDefault
()
return
false
}
handleClientError
(
event
.
error
,
[])
}
function
onUnhandledRejection
(
ev
:
WindowEventMap
[
'unhandledrejection'
]):
void
{
const
reason
=
ev
?.
reason
if
(
isNextRouterError
(
reason
))
{
ev
.
preventDefault
()
return
}
let
error
=
reason
if
(
error
&&
!
isError
(
error
))
{
error
=
createUnhandledError
(
error
+
''
)
}
rejectionQueue
.
push
(
error
)
for
(
const
handler
of
rejectionHandlers
)
{
handler
(
error
)
}
}
export
function
handleGlobalErrors
()
{
if
(
typeof
window
!==
'undefined'
)
{
try
{
...
...
@@ -67,41 +93,7 @@ export function handleGlobalErrors() {
Error
.
stackTraceLimit
=
50
}
catch
{}
window
.
addEventListener
(
'error'
,
(
event
:
WindowEventMap
[
'error'
]):
void
|
boolean
=>
{
if
(
isNextRouterError
(
event
.
error
))
{
event
.
preventDefault
()
return
false
}
handleClientError
(
event
.
error
,
[])
}
)
window
.
addEventListener
(
'unhandledrejection'
,
(
ev
:
WindowEventMap
[
'unhandledrejection'
]):
void
=>
{
const
reason
=
ev
?.
reason
if
(
isNextRouterError
(
reason
))
{
ev
.
preventDefault
()
return
}
if
(
!
reason
||
!
(
reason
instanceof
Error
)
||
typeof
reason
.
stack
!==
'string'
)
{
// A non-error was thrown, we don't have anything to show. :-(
return
}
const
e
=
reason
rejectionQueue
.
push
(
e
)
for
(
const
handler
of
rejectionHandlers
)
{
handler
(
e
)
}
}
)
window
.
addEventListener
(
'error'
,
onUnhandledError
)
window
.
addEventListener
(
'unhandledrejection'
,
onUnhandledRejection
)
}
}
packages/next/src/client/index.tsx
View file @
064970e0
/* global location */
// imports polyfill from `@next/polyfill-module` after build.
import
'../build/polyfills/polyfill-module'
import
type
Router
from
'../shared/lib/router/router'
import
type
{
AppComponent
,
...
...
@@ -46,7 +45,7 @@ import {
SearchParamsContext
,
PathParamsContext
,
}
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
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'
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(() =>
.
readonly
()
.
optional
(),
taint
:
z
.
boolean
().
optional
(),
reactOwnerStack
:
z
.
boolean
().
optional
(),
prerenderEarlyExit
:
z
.
boolean
().
optional
(),
proxyTimeout
:
z
.
number
().
gte
(
0
).
optional
(),
scrollRestoration
:
z
.
boolean
().
optional
(),
...
...
packages/next/src/server/config-shared.ts
View file @
064970e0
...
...
@@ -462,6 +462,12 @@ export interface ExperimentalConfig {
*/
taint
?:
boolean
/**
* Enables leveraging experimental captureOwnerStack API in React,
* to create a better stack trace for React errors.
*/
reactOwnerStack
?:
boolean
serverActions
?:
{
/**
* Allows adjusting body parser size limit for server actions.
...
...
@@ -1141,6 +1147,7 @@ export const defaultConfig: NextConfig = {
process
.
env
.
__NEXT_TEST_MODE
&&
process
.
env
.
__NEXT_EXPERIMENTAL_PPR
===
'true'
),
reactOwnerStack
:
false
,
webpackBuildWorker
:
undefined
,
webpackMemoryOptimizations
:
false
,
optimizeServerReact
:
true
,
...
...
test/development/acceptance-app/ReactRefreshLogBox.test.ts
View file @
064970e0
...
...
@@ -4,7 +4,6 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import
{
check
,
describeVariants
as
describe
,
expandCallStack
,
getRedboxCallStackCollapsed
,
retry
,
}
from
'next-test-utils'
...
...
@@ -777,7 +776,7 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
await
cleanup
()
})
test
(
'Call stack
count
for client error'
,
async
()
=>
{
test
(
'Call stack for client error'
,
async
()
=>
{
const
{
session
,
browser
,
cleanup
}
=
await
sandbox
(
next
,
new
Map
([
...
...
@@ -796,25 +795,30 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
])
)
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const
callStackFrames
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
try
{
await
session
.
assertHasRedbox
()
expect
(
callStackFrames
.
length
).
toBeGreaterThan
(
9
)
// 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')`
)
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
)
expect
(
moduleGroup
.
length
).
toBeGreaterThan
(
0
)
await
expect
(
browser
.
hasElementByCssSelector
(
'[data-nextjs-data-runtime-error-collapsed-action]'
)
).
resolves
.
toEqual
(
false
)
await
cleanup
()
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
const
stackFrames
=
(
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
()))
).
filter
(
Boolean
)
expect
(
stackFrames
).
toEqual
([])
}
finally
{
await
cleanup
()
}
})
test
(
'Call stack for server error'
,
async
()
=>
{
...
...
@@ -849,20 +853,10 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox app %s', () => {
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
const
stackFrames
=
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())
)
expect
(
stackFrames
).
toEqual
(
// TODO: Show useful stack
[
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
''
,
''
,
''
,
''
,
]
)
const
stackFrames
=
(
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
()))
).
filter
(
Boolean
)
expect
(
stackFrames
).
toEqual
([])
}
finally
{
await
cleanup
()
}
...
...
test/development/acceptance/ReactRefreshLogBox.test.ts
View file @
064970e0
/* eslint-env jest */
import
{
sandbox
}
from
'development-sandbox'
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
{
outdent
}
from
'outdent'
...
...
@@ -765,8 +765,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Expect more than the default amount of frames
// The default stackTraceLimit results in max 9 [data-nextjs-call-stack-frame] elements
const
callStackFrames
=
await
browser
.
elementsByCss
(
...
...
@@ -805,7 +803,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
)
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
let
callStackFrames
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
...
...
@@ -835,7 +832,6 @@ describe.each(['default', 'turbo'])('ReactRefreshLogBox %s', () => {
])
)
await
session
.
assertHasRedbox
()
await
expandCallStack
(
browser
)
// Should still show the errored line in source code
const
source
=
await
session
.
getRedboxSource
()
...
...
test/development/app-dir/dynamic-error-trace/index.test.ts
View file @
064970e0
import
{
nextTestSetup
}
from
'e2e-utils'
import
{
assertHasRedbox
,
shouldRunTurboDevTest
,
getRedboxSource
,
}
from
'next-test-utils'
import
{
assertHasRedbox
,
getRedboxSource
}
from
'next-test-utils'
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'
,
()
=>
{
const
{
next
,
skipped
}
=
nextTestSetup
({
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
,
})
if
(
skipped
)
return
...
...
@@ -40,20 +29,15 @@ describe('app dir - dynamic error trace', () => {
const
stackFrameElements
=
await
browser
.
elementsByCss
(
'[data-nextjs-call-stack-frame]'
)
const
stackFrames
=
await
Promise
.
all
(
// TODO: Why is this text empty?
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())
)
expect
(
stackFrames
).
toEqual
(
// TODO: Show useful stack
[
// Internal frames of React.
// Feel free to adjust until we show useful stacks.
''
,
''
,
''
,
''
,
]
const
stackFramesContent
=
// TODO: Why is this text empty?
(
await
Promise
.
all
(
stackFrameElements
.
map
((
f
)
=>
f
.
innerText
())))
// Filter out the frames having code snippet but without methodName and source
.
filter
(
Boolean
)
.
join
(
'
\
n'
)
// TODO: Show useful stack
expect
(
normalizeStackTrace
(
stackFramesContent
)).
toMatchInlineSnapshot
(
isReactExperimental
?
`""`
:
`""`
)
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(
.
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
(
browser
:
BrowserInterface
):
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