Unverified Commit 527fe7a0 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add graceful error boundary for bots requests (#78298)

parent f9a12ba5
...@@ -46,6 +46,7 @@ import { ...@@ -46,6 +46,7 @@ import {
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError, RedirectType } from './redirect-error' import { isRedirectError, RedirectType } from './redirect-error'
import { pingVisibleLinks } from './links' import { pingVisibleLinks } from './links'
import GracefulDegradeBoundary from './errors/graceful-degrade-boundary'
const globalMutable: { const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
...@@ -515,7 +516,9 @@ function Router({ ...@@ -515,7 +516,9 @@ function Router({
} else { } else {
// If gracefully degrading is applied in production, // If gracefully degrading is applied in production,
// leave the app as it is rather than caught by GlobalError boundary. // leave the app as it is rather than caught by GlobalError boundary.
if (!gracefullyDegrade) { if (gracefullyDegrade) {
content = <GracefulDegradeBoundary>{content}</GracefulDegradeBoundary>
} else {
content = ( content = (
<ErrorBoundary <ErrorBoundary
errorComponent={globalError[0]} errorComponent={globalError[0]}
......
'use client'
import { Component, createRef, type ReactNode } from 'react'
interface ErrorBoundaryProps {
children: ReactNode
}
interface ErrorBoundaryState {
hasError: boolean
}
function getDomNodeAttributes(node: HTMLElement): Record<string, string> {
const result: Record<string, string> = {}
for (let i = 0; i < node.attributes.length; i++) {
const attr = node.attributes[i]
result[attr.name] = attr.value
}
return result
}
export class GracefulDegradeBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
private rootHtml: string
private htmlAttributes: Record<string, string>
private htmlRef: React.RefObject<HTMLHtmlElement | null>
constructor(props: ErrorBoundaryProps) {
super(props)
this.state = { hasError: false }
this.rootHtml = ''
this.htmlAttributes = {}
this.htmlRef = createRef<HTMLHtmlElement>()
}
static getDerivedStateFromError(_: unknown): ErrorBoundaryState {
return { hasError: true }
}
componentDidMount() {
const htmlNode = this.htmlRef.current
if (this.state.hasError && htmlNode) {
// Reapply the cached HTML attributes to the root element
Object.entries(this.htmlAttributes).forEach(([key, value]) => {
htmlNode.setAttribute(key, value)
})
}
}
render() {
const { hasError } = this.state
// Cache the root HTML content on the first render
if (typeof window !== 'undefined' && !this.rootHtml) {
this.rootHtml = document.documentElement.innerHTML
this.htmlAttributes = getDomNodeAttributes(document.documentElement)
}
if (hasError) {
// Render the current HTML content without hydration
return (
<html
ref={this.htmlRef}
suppressHydrationWarning
dangerouslySetInnerHTML={{
__html: this.rootHtml,
}}
/>
)
}
return this.props.children
}
}
export default GracefulDegradeBoundary
'use client'
export default function Page() {
if (typeof window !== 'undefined') {
throw new Error('boom')
}
return <p>fine</p>
}
'use client'
export default function Page() {
if (typeof window !== 'undefined') {
throw new Error('boom')
}
return <p>fine</p>
}
'use client'
import dynamic from 'next/dynamic'
export const Large = dynamic(() => import('./content'))
'use client'
export default function Large() {
return <p>large test content</p>
}
'use client'
import { Large } from './async-content'
export default function Page() {
return (
<div className="page">
<p>hello world von server</p>
<Large />
</div>
)
}
export { default } from './page-client'
export const dynamic = 'force-dynamic'
'use client'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html className="layout-cls">
<body className="body-cls">{children}</body>
</html>
)
}
// Duplicate the test file of graceful-degrade-error-bot.test.ts since we need to
// restart with a new browser context for UA setting. Otherwise the browser context
// will not be closed and reset properly. TODO: investigate why browser.close didn't help.
import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from '../delete-dynamic-chunk'
describe('graceful-degrade - custom-error - non bot', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Delete client chunks to simulate chunk loading failure
beforeAll(() => {
deleteBrowserDynamicChunks(next)
})
it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => {
const browser = await next.browser('/blog')
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Failed to load resource./)
// Should show the same layout content
const html = await browser.elementByCss('html')
const body = await browser.elementByCss('body')
expect(await html.getAttribute('class')).toBe('layout-cls')
expect(await body.getAttribute('class')).toBe('body-cls')
// Show the custom error boundary text
const errorBoundaryText = await browser
.elementByCss('.error-boundary')
.text()
expect(errorBoundaryText).toMatch(/Custom error boundary/)
})
})
import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from '../delete-dynamic-chunk'
describe('graceful-degrade - custom error', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Delete client chunks to simulate chunk loading failure
beforeAll(() => {
deleteBrowserDynamicChunks(next)
})
it('should degrade to graceful error when chunk loading fails in ssr for bot', async () => {
const browser = await next.browser('/blog', {
userAgent: 'Googlebot',
})
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Failed to load resource./)
// Should show the original content
const html = await browser.elementByCss('html')
const body = await browser.elementByCss('body')
expect(await html.getAttribute('class')).toBe('layout-cls')
expect(await body.getAttribute('class')).toBe('body-cls')
// Do not contain the custom error boundary text
const bodyText = await body.text()
expect(bodyText).not.toMatch(/Custom error boundary/)
})
})
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
// will not be closed and reset properly. TODO: investigate why browser.close didn't help. // will not be closed and reset properly. TODO: investigate why browser.close didn't help.
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from '../delete-dynamic-chunk' import { deleteBrowserDynamicChunks } from './delete-dynamic-chunk'
describe('graceful-degrade - non bot', () => { describe('graceful-degrade - non bot', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -16,7 +16,7 @@ describe('graceful-degrade - non bot', () => { ...@@ -16,7 +16,7 @@ describe('graceful-degrade - non bot', () => {
}) })
it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => { it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => {
const browser = await next.browser('/') const browser = await next.browser('/chunk-loading-failed')
const logs = await browser.log() const logs = await browser.log()
const errors = logs const errors = logs
...@@ -36,4 +36,20 @@ describe('graceful-degrade - non bot', () => { ...@@ -36,4 +36,20 @@ describe('graceful-degrade - non bot', () => {
/Application error: a client-side exception has occurred while loading/ /Application error: a client-side exception has occurred while loading/
) )
}) })
it('should show error boundary when browser errors when error boundary is defined', async () => {
const browser = await next.browser('/browser-crash-error-boundary')
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Error: boom/)
const bodyText = await browser.elementByCss('body').text()
expect(bodyText).toMatch(/Custom error boundary/)
expect(bodyText).not.toMatch(/fine/)
})
}) })
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from '../delete-dynamic-chunk' import { deleteBrowserDynamicChunks } from './delete-dynamic-chunk'
describe('graceful-degrade', () => { describe('graceful-degrade', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -12,7 +12,7 @@ describe('graceful-degrade', () => { ...@@ -12,7 +12,7 @@ describe('graceful-degrade', () => {
}) })
it('should degrade to graceful error when chunk loading fails in ssr for bot', async () => { it('should degrade to graceful error when chunk loading fails in ssr for bot', async () => {
const browser = await next.browser('/', { const browser = await next.browser('/chunk-loading-failed', {
userAgent: 'Googlebot', userAgent: 'Googlebot',
}) })
...@@ -35,4 +35,24 @@ describe('graceful-degrade', () => { ...@@ -35,4 +35,24 @@ describe('graceful-degrade', () => {
/Application error: a client-side exception has occurred while loading/ /Application error: a client-side exception has occurred while loading/
) )
}) })
it('should preserve the ssr html when browser errors for bot', async () => {
const browser = await next.browser('/browser-crash', {
userAgent: 'Googlebot',
})
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Error: boom/)
const bodyText = await browser.elementByCss('body').text()
expect(bodyText).not.toMatch(
/Application error: a client-side exception has occurred while loading/
)
expect(bodyText).toMatch(/fine/)
})
}) })
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
"packages/next/src/client/set-attributes-from-props.ts", "packages/next/src/client/set-attributes-from-props.ts",
"packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts", "packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.ts",
"packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts", "packages/next/src/build/webpack/loaders/next-style-loader/runtime/injectStylesIntoStyleTag.ts",
"packages/next/src/client/app-bootstrap.ts" "packages/next/src/client/app-bootstrap.ts",
"packages/next/src/client/components/errors/graceful-degrade-boundary.tsx"
], ],
"ban-script-content-assignments": ["packages/next/src/client/script.tsx"], "ban-script-content-assignments": ["packages/next/src/client/script.tsx"],
"ban-script-src-assignments": [ "ban-script-src-assignments": [
......
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