Unverified Commit 1797fc50 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fall back to default components when a top-level error occurs (#24079)

This fixes an internal server error showing when a top-level error occurs in `_app` in development instead of the dev overlay. This includes the failing test case from https://github.com/vercel/next.js/pull/24069 and also ensures the overlay is cleared when the error is corrected. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added

Fixes: https://github.com/vercel/next.js/issues/24070
Closes: https://github.com/vercel/next.js/pull/24069
parent 1e207301
...@@ -254,50 +254,49 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -254,50 +254,49 @@ export default async (opts: { webpackHMR?: any } = {}) => {
webpackHMR = opts.webpackHMR webpackHMR = opts.webpackHMR
} }
const appEntrypoint = await pageLoader.routeLoader.whenEntrypoint('/_app') let initialErr = hydrateErr
if ('error' in appEntrypoint) {
throw appEntrypoint.error
}
const { component: app, exports: mod } = appEntrypoint try {
CachedApp = app as AppComponent const appEntrypoint = await pageLoader.routeLoader.whenEntrypoint('/_app')
if ('error' in appEntrypoint) {
if (mod && mod.reportWebVitals) { throw appEntrypoint.error
onPerfEntry = ({ }
id,
name,
startTime,
value,
duration,
entryType,
entries,
}): void => {
// Combines timestamp with random number for unique ID
const uniqueID: string = `${Date.now()}-${
Math.floor(Math.random() * (9e12 - 1)) + 1e12
}`
let perfStartEntry: string | undefined
if (entries && entries.length) {
perfStartEntry = entries[0].startTime
}
mod.reportWebVitals({ const { component: app, exports: mod } = appEntrypoint
id: id || uniqueID, CachedApp = app as AppComponent
if (mod && mod.reportWebVitals) {
onPerfEntry = ({
id,
name, name,
startTime: startTime || perfStartEntry, startTime,
value: value == null ? duration : value, value,
label: duration,
entryType === 'mark' || entryType === 'measure' entryType,
? 'custom' entries,
: 'web-vital', }): void => {
}) // Combines timestamp with random number for unique ID
} const uniqueID: string = `${Date.now()}-${
} Math.floor(Math.random() * (9e12 - 1)) + 1e12
}`
let perfStartEntry: string | undefined
if (entries && entries.length) {
perfStartEntry = entries[0].startTime
}
let initialErr = hydrateErr mod.reportWebVitals({
id: id || uniqueID,
name,
startTime: startTime || perfStartEntry,
value: value == null ? duration : value,
label:
entryType === 'mark' || entryType === 'measure'
? 'custom'
: 'web-vital',
})
}
}
try {
const pageEntrypoint = const pageEntrypoint =
// The dev server fails to serve script assets when there's a hydration // The dev server fails to serve script assets when there's a hydration
// error, so we need to skip waiting for the entrypoint. // error, so we need to skip waiting for the entrypoint.
......
...@@ -35,6 +35,22 @@ export type LoadComponentsReturnType = { ...@@ -35,6 +35,22 @@ export type LoadComponentsReturnType = {
ComponentMod: any ComponentMod: any
} }
export async function loadDefaultErrorComponents(distDir: string) {
const Document = interopDefault(require('next/dist/pages/_document'))
const App = interopDefault(require('next/dist/pages/_app'))
const ComponentMod = require('next/dist/pages/_error')
const Component = interopDefault(ComponentMod)
return {
App,
Document,
Component,
buildManifest: require(join(distDir, BUILD_MANIFEST)),
reactLoadableManifest: require(join(distDir, REACT_LOADABLE_MANIFEST)),
ComponentMod,
}
}
export async function loadComponents( export async function loadComponents(
distDir: string, distDir: string,
pathname: string, pathname: string,
......
...@@ -52,7 +52,11 @@ import { ...@@ -52,7 +52,11 @@ import {
import { DomainLocales, isTargetLikeServerless, NextConfig } from './config' import { DomainLocales, isTargetLikeServerless, NextConfig } from './config'
import pathMatch from '../lib/router/utils/path-match' import pathMatch from '../lib/router/utils/path-match'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync' import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components' import {
loadComponents,
LoadComponentsReturnType,
loadDefaultErrorComponents,
} from './load-components'
import { normalizePagePath } from './normalize-page-path' import { normalizePagePath } from './normalize-page-path'
import { RenderOpts, RenderOptsPartial, renderToHTML } from './render' import { RenderOpts, RenderOptsPartial, renderToHTML } from './render'
import { getPagePath, requireFontManifest } from './require' import { getPagePath, requireFontManifest } from './require'
...@@ -1964,38 +1968,38 @@ export default class Server { ...@@ -1964,38 +1968,38 @@ export default class Server {
_pathname: string, _pathname: string,
query: ParsedUrlQuery = {} query: ParsedUrlQuery = {}
) { ) {
let result: null | FindComponentsResult = null let html: string | null
try {
let result: null | FindComponentsResult = null
const is404 = res.statusCode === 404 const is404 = res.statusCode === 404
let using404Page = false let using404Page = false
// use static 404 page if available and is 404 response // use static 404 page if available and is 404 response
if (is404) { if (is404) {
result = await this.findPageComponents('/404', query) result = await this.findPageComponents('/404', query)
using404Page = result !== null using404Page = result !== null
} }
let statusPage = `/${res.statusCode}` let statusPage = `/${res.statusCode}`
if (!result && STATIC_STATUS_PAGES.includes(statusPage)) { if (!result && STATIC_STATUS_PAGES.includes(statusPage)) {
result = await this.findPageComponents(statusPage, query) result = await this.findPageComponents(statusPage, query)
} }
if (!result) { if (!result) {
result = await this.findPageComponents('/_error', query) result = await this.findPageComponents('/_error', query)
statusPage = '/_error' statusPage = '/_error'
} }
if ( if (
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'production' &&
!using404Page && !using404Page &&
(await this.hasPage('/_error')) && (await this.hasPage('/_error')) &&
!(await this.hasPage('/404')) !(await this.hasPage('/404'))
) { ) {
this.customErrorNo404Warn() this.customErrorNo404Warn()
} }
let html: string | null
try {
try { try {
html = await this.renderToHTMLWithComponents( html = await this.renderToHTMLWithComponents(
req, req,
...@@ -2016,6 +2020,23 @@ export default class Server { ...@@ -2016,6 +2020,23 @@ export default class Server {
} catch (renderToHtmlError) { } catch (renderToHtmlError) {
console.error(renderToHtmlError) console.error(renderToHtmlError)
res.statusCode = 500 res.statusCode = 500
if (this.renderOpts.dev) {
const fallbackResult = await loadDefaultErrorComponents(this.distDir)
return this.renderToHTMLWithComponents(
req,
res,
'/_error',
{
query,
components: fallbackResult,
},
{
...this.renderOpts,
err,
}
)
}
html = 'Internal Server Error' html = 'Internal Server Error'
} }
return html return html
......
...@@ -1260,3 +1260,44 @@ test('<Link> component props errors', async () => { ...@@ -1260,3 +1260,44 @@ test('<Link> component props errors', async () => {
await cleanup() await cleanup()
}) })
test('_app top level error shows logbox', async () => {
const [session, cleanup] = await sandbox(
undefined,
new Map([
[
'pages/_app.js',
`
throw new Error("test");
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp
`,
],
])
)
expect(await session.hasRedbox(true)).toBe(true)
expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
"pages/_app.js (2:16) @ eval
1 |
> 2 | throw new Error(\\"test\\");
| ^
3 | function MyApp({ Component, pageProps }) {
4 | return <Component {...pageProps} />;
5 | }"
`)
await session.patch(
'pages/_app.js',
`
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp
`
)
expect(await session.hasRedbox()).toBe(false)
await cleanup()
})
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