Unverified Commit cd570982 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Handle development error when Server Component throws (#38550)

Handles the case where an error is introduced which causes a Fast Refresh and then it's fixed.


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent c2b40d07
...@@ -212,19 +212,6 @@ function ServerRoot({ cacheKey }: { cacheKey: string }) { ...@@ -212,19 +212,6 @@ function ServerRoot({ cacheKey }: { cacheKey: string }) {
return root return root
} }
function ErrorOverlay({
children,
}: React.PropsWithChildren<{}>): React.ReactElement {
if (process.env.NODE_ENV === 'production') {
return <>{children}</>
} else {
const {
ReactDevOverlay,
} = require('next/dist/compiled/@next/react-dev-overlay/dist/client')
return <ReactDevOverlay globalOverlay>{children}</ReactDevOverlay>
}
}
function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement { function Root({ children }: React.PropsWithChildren<{}>): React.ReactElement {
if (process.env.__NEXT_TEST_MODE) { if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
...@@ -247,12 +234,10 @@ function RSCComponent() { ...@@ -247,12 +234,10 @@ function RSCComponent() {
export function hydrate() { export function hydrate() {
renderReactElement(appElement!, () => ( renderReactElement(appElement!, () => (
<ErrorOverlay> <React.StrictMode>
<React.StrictMode> <Root>
<Root> <RSCComponent />
<RSCComponent /> </Root>
</Root> </React.StrictMode>
</React.StrictMode>
</ErrorOverlay>
)) ))
} }
...@@ -36,6 +36,19 @@ export function fetchServerResponse( ...@@ -36,6 +36,19 @@ export function fetchServerResponse(
return createFromFetch(fetchFlight(url, flightRouterStateData)) return createFromFetch(fetchFlight(url, flightRouterStateData))
} }
function ErrorOverlay({
children,
}: React.PropsWithChildren<{}>): React.ReactElement {
if (process.env.NODE_ENV === 'production') {
return <>{children}</>
} else {
const {
ReactDevOverlay,
} = require('next/dist/compiled/@next/react-dev-overlay/dist/client')
return <ReactDevOverlay globalOverlay>{children}</ReactDevOverlay>
}
}
// TODO: move this back into AppRouter // TODO: move this back into AppRouter
let initialParallelRoutes: CacheNode['parallelRoutes'] = let initialParallelRoutes: CacheNode['parallelRoutes'] =
typeof window === 'undefined' ? null! : new Map() typeof window === 'undefined' ? null! : new Map()
...@@ -248,7 +261,7 @@ export default function AppRouter({ ...@@ -248,7 +261,7 @@ export default function AppRouter({
url: canonicalUrl, url: canonicalUrl,
}} }}
> >
{cache.subTreeData} <ErrorOverlay>{cache.subTreeData}</ErrorOverlay>
{hotReloader} {hotReloader}
</AppTreeContext.Provider> </AppTreeContext.Provider>
</AppRouterContext.Provider> </AppRouterContext.Provider>
......
import { useCallback, useContext, useEffect, useRef } from 'react' import {
useCallback,
useContext,
useEffect,
useRef,
// @ts-expect-error TODO: startTransition exists
startTransition,
} from 'react'
import { FullAppTreeContext } from '../../shared/lib/app-router-context' import { FullAppTreeContext } from '../../shared/lib/app-router-context'
import { import {
register, register,
unregister,
onBuildError, onBuildError,
onBuildOk, onBuildOk,
onRefresh, onRefresh,
...@@ -305,7 +313,15 @@ function processMessage( ...@@ -305,7 +313,15 @@ function processMessage(
clientId: __nextDevClientId, clientId: __nextDevClientId,
}) })
) )
return router.reload() if (hadRuntimeError) {
return window.location.reload()
}
startTransition(() => {
router.reload()
onRefresh()
})
return
} }
case 'reloadPage': { case 'reloadPage': {
sendMessage( sendMessage(
...@@ -393,6 +409,16 @@ export default function HotReload({ assetPrefix }: { assetPrefix: string }) { ...@@ -393,6 +409,16 @@ export default function HotReload({ assetPrefix }: { assetPrefix: string }) {
useEffect(() => { useEffect(() => {
register() register()
const onError = () => {
hadRuntimeError = true
}
window.addEventListener('error', onError)
window.addEventListener('unhandledrejection', onError)
return () => {
unregister()
window.removeEventListener('error', onError)
window.removeEventListener('unhandledrejection', onError)
}
}, []) }, [])
useEffect(() => { useEffect(() => {
......
...@@ -260,6 +260,16 @@ function processMessage(e) { ...@@ -260,6 +260,16 @@ function processMessage(e) {
) )
return handleSuccess() return handleSuccess()
} }
case 'serverComponentChanges': {
sendMessage(
JSON.stringify({
event: 'server-component-reload-page',
clientId: window.__nextDevClientId,
})
)
return window.location.reload()
}
default: { default: {
if (customHmrEventHandler) { if (customHmrEventHandler) {
customHmrEventHandler(obj) customHmrEventHandler(obj)
......
...@@ -1982,6 +1982,11 @@ export default async function (task) { ...@@ -1982,6 +1982,11 @@ export default async function (task) {
opts opts
) )
await task.watch('server/**/*.+(wasm)', 'server_wasm', opts) await task.watch('server/**/*.+(wasm)', 'server_wasm', opts)
await task.watch(
'../react-dev-overlay/dist/**/*.js',
'ncc_next__react_dev_overlay',
opts
)
} }
export async function shared(task, opts) { export async function shared(task, opts) {
......
...@@ -2,6 +2,8 @@ import React from 'react' ...@@ -2,6 +2,8 @@ import React from 'react'
type ErrorBoundaryProps = { type ErrorBoundaryProps = {
onError: (error: Error, componentStack: string | null) => void onError: (error: Error, componentStack: string | null) => void
globalOverlay?: boolean
isMounted?: boolean
} }
type ErrorBoundaryState = { error: Error | null } type ErrorBoundaryState = { error: Error | null }
...@@ -10,7 +12,6 @@ class ErrorBoundary extends React.PureComponent< ...@@ -10,7 +12,6 @@ class ErrorBoundary extends React.PureComponent<
ErrorBoundaryState ErrorBoundaryState
> { > {
state = { error: null } state = { error: null }
componentDidCatch( componentDidCatch(
error: Error, error: Error,
// Loosely typed because it depends on the React version and was // Loosely typed because it depends on the React version and was
...@@ -18,14 +19,26 @@ class ErrorBoundary extends React.PureComponent< ...@@ -18,14 +19,26 @@ class ErrorBoundary extends React.PureComponent<
errorInfo?: { componentStack?: string | null } errorInfo?: { componentStack?: string | null }
) { ) {
this.props.onError(error, errorInfo?.componentStack || null) this.props.onError(error, errorInfo?.componentStack || null)
this.setState({ error }) if (!this.props.globalOverlay) {
this.setState({ error })
}
} }
render() { render() {
return this.state.error // The component has to be unmounted or else it would continue to error
? // The component has to be unmounted or else it would continue to error return this.state.error ||
null (this.props.globalOverlay && this.props.isMounted) ? (
: this.props.children // When the overlay is global for the application and it wraps a component rendering `<html>`
// we have to render the html shell otherwise the shadow root will not be able to attach
this.props.globalOverlay ? (
<html>
<head></head>
<body></body>
</html>
) : null
) : (
this.props.children
)
} }
} }
......
...@@ -31,7 +31,13 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -31,7 +31,13 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
return { return {
...state, ...state,
nextId: state.nextId + 1, nextId: state.nextId + 1,
errors: [...state.errors, { id: state.nextId, event: ev }], errors: [
...state.errors.filter((err) => {
// Filter out duplicate errors
return err.event.reason !== ev.reason
}),
{ id: state.nextId, event: ev },
],
} }
} }
default: { default: {
...@@ -82,7 +88,11 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({ ...@@ -82,7 +88,11 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
return ( return (
<React.Fragment> <React.Fragment>
<ErrorBoundary onError={onComponentError}> <ErrorBoundary
globalOverlay={globalOverlay}
isMounted={isMounted}
onError={onComponentError}
>
{children ?? null} {children ?? null}
</ErrorBoundary> </ErrorBoundary>
{isMounted ? ( {isMounted ? (
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment