Unverified Commit ef579532 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Close stream when fatal error occurs (#31164)

* support custom 500 error in streaming

* remove unused imports
parent eb0bd63a
...@@ -162,6 +162,7 @@ export function createEntrypoints( ...@@ -162,6 +162,7 @@ export function createEntrypoints(
page, page,
absoluteAppPath: pages['/_app'], absoluteAppPath: pages['/_app'],
absoluteDocumentPath: pages['/_document'], absoluteDocumentPath: pages['/_document'],
absoluteErrorPath: pages['/_error'],
absolutePagePath, absolutePagePath,
isServerComponent: isFlight, isServerComponent: isFlight,
buildId, buildId,
......
...@@ -5,6 +5,7 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -5,6 +5,7 @@ export default async function middlewareRSCLoader(this: any) {
absolutePagePath, absolutePagePath,
absoluteAppPath, absoluteAppPath,
absoluteDocumentPath, absoluteDocumentPath,
absoluteErrorPath,
basePath, basePath,
isServerComponent: isServerComponentQuery, isServerComponent: isServerComponentQuery,
assetPrefix, assetPrefix,
...@@ -14,23 +15,28 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -14,23 +15,28 @@ export default async function middlewareRSCLoader(this: any) {
const isServerComponent = isServerComponentQuery === 'true' const isServerComponent = isServerComponentQuery === 'true'
const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath) const stringifiedAbsolutePagePath = stringifyRequest(this, absolutePagePath)
const stringifiedAbsoluteAppPath = stringifyRequest(this, absoluteAppPath) const stringifiedAbsoluteAppPath = stringifyRequest(this, absoluteAppPath)
const stringifiedAbsoluteErrorPath = stringifyRequest(this, absoluteErrorPath)
const stringified500PagePath = stringifyRequest(this, './pages/500')
const stringifiedAbsoluteDocumentPath = stringifyRequest( const stringifiedAbsoluteDocumentPath = stringifyRequest(
this, this,
absoluteDocumentPath absoluteDocumentPath
) )
let appDefinition = `const App = require(${stringifiedAbsoluteAppPath}).default`
let documentDefinition = `const Document = require(${stringifiedAbsoluteDocumentPath}).default`
const transformed = ` const transformed = `
import { adapter } from 'next/dist/server/web/adapter' import { adapter } from 'next/dist/server/web/adapter'
import { RouterContext } from 'next/dist/shared/lib/router-context' import { RouterContext } from 'next/dist/shared/lib/router-context'
import { renderToHTML } from 'next/dist/server/web/render' import { renderToHTML } from 'next/dist/server/web/render'
${appDefinition} import App from ${stringifiedAbsoluteAppPath}
${documentDefinition} import Document from ${stringifiedAbsoluteDocumentPath}
let ErrorPage
try {
ErrorPage = require(${stringified500PagePath}).default
} catch (_) {
ErrorPage = require(${stringifiedAbsoluteErrorPath}).default
}
const { const {
default: Page, default: Page,
config, config,
...@@ -66,6 +72,7 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -66,6 +72,7 @@ export default async function middlewareRSCLoader(this: any) {
} }
delete query.__flight__ delete query.__flight__
const req = { url: pathname }
const renderOpts = { const renderOpts = {
Component, Component,
pageConfig: config || {}, pageConfig: config || {},
...@@ -97,32 +104,51 @@ export default async function middlewareRSCLoader(this: any) { ...@@ -97,32 +104,51 @@ export default async function middlewareRSCLoader(this: any) {
const transformStream = new TransformStream() const transformStream = new TransformStream()
const writer = transformStream.writable.getWriter() const writer = transformStream.writable.getWriter()
const encoder = new TextEncoder() const encoder = new TextEncoder()
let result
let renderError
let statusCode = 200
try { try {
const result = await renderToHTML( result = await renderToHTML(
{ url: pathname }, req,
{}, {},
pathname, pathname,
query, query,
renderOpts renderOpts
) )
result.pipe({
write: str => writer.write(encoder.encode(str)),
end: () => writer.close(),
// Not implemented: cork/uncork/on/removeListener
})
} catch (err) { } catch (err) {
return new Response( renderError = err
(err || 'An error occurred while rendering ' + pathname + '.').toString(), statusCode = 500
{ }
status: 500, if (renderError) {
headers: { 'x-middleware-ssr': '1' } try {
} const errorRes = { statusCode, err: renderError }
) result = await renderToHTML(
req,
errorRes,
pathname,
query,
{ ...renderOpts, Component: ErrorPage }
)
} catch (err) {
return new Response(
(err || 'An error occurred while rendering ' + pathname + '.').toString(),
{
status: 500,
headers: { 'x-middleware-ssr': '1' }
}
)
}
} }
result.pipe({
write: str => writer.write(encoder.encode(str)),
end: () => writer.close(),
// Not implemented: cork/uncork/on/removeListener
})
return new Response(transformStream.readable, { return new Response(transformStream.readable, {
headers: { 'x-middleware-ssr': '1' } headers: { 'x-middleware-ssr': '1' },
status: statusCode
}) })
} }
......
...@@ -528,6 +528,7 @@ export default class HotReloader { ...@@ -528,6 +528,7 @@ export default class HotReloader {
page, page,
absoluteAppPath: this.pagesMapping['/_app'], absoluteAppPath: this.pagesMapping['/_app'],
absoluteDocumentPath: this.pagesMapping['/_document'], absoluteDocumentPath: this.pagesMapping['/_document'],
absoluteErrorPath: this.pagesMapping['/_error'],
absolutePagePath, absolutePagePath,
isServerComponent, isServerComponent,
buildId: this.buildId, buildId: this.buildId,
......
const page = () => 'page with err'
page.getInitialProps = () => {
throw new Error('oops')
}
export default page
let did = false
export default function Error() {
if (!did && typeof window === 'undefined') {
did = true
throw new Error('oops')
}
}
import { Suspense } from 'react'
let did = false
function Error() {
if (!did && typeof window === 'undefined') {
did = true
throw new Error('broken page')
}
}
export default function page() {
return (
<>
<h1>Hey Error</h1>
<Suspense>
<Error />
</Suspense>
</>
)
}
...@@ -24,6 +24,7 @@ const nativeModuleTestAppDir = join(__dirname, '../unsupported-native-module') ...@@ -24,6 +24,7 @@ const nativeModuleTestAppDir = join(__dirname, '../unsupported-native-module')
const distDir = join(__dirname, '../app/.next') const distDir = join(__dirname, '../app/.next')
const documentPage = new File(join(appDir, 'pages/_document.jsx')) const documentPage = new File(join(appDir, 'pages/_document.jsx'))
const appPage = new File(join(appDir, 'pages/_app.js')) const appPage = new File(join(appDir, 'pages/_app.js'))
const error500Page = new File(join(appDir, 'pages/500.js'))
const documentWithGip = ` const documentWithGip = `
import { Html, Head, Main, NextScript } from 'next/document' import { Html, Head, Main, NextScript } from 'next/document'
...@@ -55,6 +56,12 @@ function App({ Component, pageProps }) { ...@@ -55,6 +56,12 @@ function App({ Component, pageProps }) {
export default App export default App
` `
const page500 = `
export default function Page500() {
return 'custom-500-page'
}
`
async function nextBuild(dir) { async function nextBuild(dir) {
return await _nextBuild(dir, [], { return await _nextBuild(dir, [], {
stdout: true, stdout: true,
...@@ -100,11 +107,13 @@ describe('concurrentFeatures - prod', () => { ...@@ -100,11 +107,13 @@ describe('concurrentFeatures - prod', () => {
const context = { appDir } const context = { appDir }
beforeAll(async () => { beforeAll(async () => {
error500Page.write(page500)
context.appPort = await findPort() context.appPort = await findPort()
await nextBuild(context.appDir) await nextBuild(context.appDir)
context.server = await nextStart(context.appDir, context.appPort) context.server = await nextStart(context.appDir, context.appPort)
}) })
afterAll(async () => { afterAll(async () => {
error500Page.delete()
await killApp(context.server) await killApp(context.server)
}) })
...@@ -155,10 +164,12 @@ describe('concurrentFeatures - dev', () => { ...@@ -155,10 +164,12 @@ describe('concurrentFeatures - dev', () => {
const context = { appDir } const context = { appDir }
beforeAll(async () => { beforeAll(async () => {
error500Page.write(page500)
context.appPort = await findPort() context.appPort = await findPort()
context.server = await nextDev(context.appDir, context.appPort) context.server = await nextDev(context.appDir, context.appPort)
}) })
afterAll(async () => { afterAll(async () => {
error500Page.delete()
await killApp(context.server) await killApp(context.server)
}) })
...@@ -217,6 +228,7 @@ async function runBasicTests(context) { ...@@ -217,6 +228,7 @@ async function runBasicTests(context) {
) )
const path404HTML = await renderViaHTTP(context.appPort, '/404') const path404HTML = await renderViaHTTP(context.appPort, '/404')
const path500HTML = await renderViaHTTP(context.appPort, '/err')
const pathNotFoundHTML = await renderViaHTTP( const pathNotFoundHTML = await renderViaHTTP(
context.appPort, context.appPort,
'/this-is-not-found' '/this-is-not-found'
...@@ -230,6 +242,7 @@ async function runBasicTests(context) { ...@@ -230,6 +242,7 @@ async function runBasicTests(context) {
expect(dynamicRouteHTML2).toContain('[pid]') expect(dynamicRouteHTML2).toContain('[pid]')
expect(path404HTML).toContain('custom-404-page') expect(path404HTML).toContain('custom-404-page')
expect(path500HTML).toContain('custom-500-page')
expect(pathNotFoundHTML).toContain('custom-404-page') expect(pathNotFoundHTML).toContain('custom-404-page')
}) })
......
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