Unverified Commit 73764165 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: align chunk loading error name (#86593)

- Set `error.name` just like Webpack does
- Add some tests

<img width="1854" height="451" alt="Bildschirmfoto 2025-11-28 um 10 44 06" src="https://github.com/user-attachments/assets/8cadd60e-2a7f-4715-9c39-66453fe400f4" />


<img width="1865" height="564" alt="Bildschirmfoto 2025-11-27 um 16 52 34" src="https://github.com/user-attachments/assets/959bdb52-83a5-4b73-9d5f-b727f8715a6e" />
parent 4390c7b4
......@@ -910,10 +910,12 @@ jobs:
export IS_WEBPACK_TEST=1
BROWSER_NAME=firefox node run-tests.js \
test/production/pages-dir/production/test/index.test.ts
test/production/pages-dir/production/test/index.test.ts \
test/production/chunk-load-failure/chunk-load-failure.test.ts
NEXT_TEST_MODE=start BROWSER_NAME=safari node run-tests.js \
test/production/pages-dir/production/test/index.test.ts \
test/production/chunk-load-failure/chunk-load-failure.test.ts \
test/e2e/basepath/basepath.test.ts \
test/e2e/basepath/error-pages.test.ts
......
export default function Async() {
return 'this is a lazy loaded async component'
}
'use client'
import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const Async = dynamic(() => import('./async'), { ssr: false })
export default function Page() {
return (
<>
<Suspense fallback={<div>Loading...</div>}>
<Async />
</Suspense>
</>
)
}
export default function Layout({ children }) {
return (
<html lang="en">
<head />
<body>{children}</body>
</html>
)
}
'use client'
export default function Page() {
return <>this is other</>
}
import { nextTestSetup } from 'e2e-utils'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import path from 'path'
import fs from 'fs'
import { retry } from 'next-test-utils'
describe('chunk-load-failure', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function getNextDynamicChunk() {
const chunksPath = path.join(next.testDir, '.next/static/')
const browserChunks = await recursiveReadDir(chunksPath, {
pathnameFilter: (f) => /\.js$/.test(f),
})
let nextDynamicChunks = browserChunks.filter((f) =>
fs
.readFileSync(path.join(chunksPath, f), 'utf8')
.includes('this is a lazy loaded async component')
)
expect(nextDynamicChunks).toHaveLength(1)
return nextDynamicChunks[0]
}
it('should report async chunk load failures', async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + nextDynamicChunk, async (route) => {
await route.abort('connectionreset')
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toMatch(
/Application error: a client-side exception has occurred while loading/
)
})
expect(pageError).toBeDefined()
expect(pageError.name).toBe('ChunkLoadError')
if (process.env.IS_TURBOPACK_TEST) {
expect(pageError.message).toStartWith(
'Failed to load chunk /_next/static/' + nextDynamicChunk
)
} else {
expect(pageError.message).toMatch(/^Loading chunk \S+ failed./)
expect(pageError.message).toContain('/_next/static/' + nextDynamicChunk)
}
})
it('should report aborted chunks when navigating away', async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let resolve
try {
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + nextDynamicChunk, async (route) => {
// deterministically ensure that the async chunk is still loading during the navigation
await new Promise((r) => {
resolve = r
})
})
page.on('pageerror', (error: Error) => {
console.log('pageerror', error)
})
},
})
await browser.get(next.url + '/other')
let body = await browser.elementByCss('body')
expect(await body.text()).toMatch('this is other')
const browserLogs = (await browser.log()).filter(
(m) => m.source === 'warning' || m.source === 'error'
)
if (process.env.BROWSER_NAME === 'firefox') {
expect(browserLogs).toContainEqual(
expect.objectContaining({
message: expect.stringContaining(
'Loading failed for the <script> with source'
),
})
)
} else {
// Chrome and Safari doesn't show any errors or warnings here
expect(browserLogs).toBeEmpty()
}
} finally {
// prevent hanging
resolve?.()
}
})
})
/** @type {import('next').NextConfig} */
const nextConfig = {}
export default nextConfig
......@@ -250,7 +250,7 @@ function loadChunkByUrlInternal(
thenable,
loadedChunk
)
entry = thenable.then(resolve).catch((error) => {
entry = thenable.then(resolve).catch((cause) => {
let loadReason: string
switch (sourceType) {
case SourceType.Runtime:
......@@ -268,16 +268,14 @@ function loadChunkByUrlInternal(
(sourceType) => `Unknown source type: ${sourceType}`
)
}
throw new Error(
let error = new Error(
`Failed to load chunk ${chunkUrl} ${loadReason}${
error ? `: ${error}` : ''
cause ? `: ${cause}` : ''
}`,
error
? {
cause: error,
}
: undefined
cause ? { cause } : undefined
)
error.name = 'ChunkLoadError'
throw error
})
instrumentedBackendLoadChunks.set(thenable, entry)
}
......
......@@ -99,16 +99,16 @@ function loadRuntimeChunkPath(
const chunkModules: CompressedModuleFactories = require(resolved)
installCompressedModuleFactories(chunkModules, 0, moduleFactories)
loadedChunks.add(chunkPath)
} catch (e) {
} catch (cause) {
let errorMessage = `Failed to load chunk ${chunkPath}`
if (sourcePath) {
errorMessage += ` from runtime for chunk ${sourcePath}`
}
throw new Error(errorMessage, {
cause: e,
})
const error = new Error(errorMessage, { cause })
error.name = 'ChunkLoadError'
throw error
}
}
......@@ -133,15 +133,13 @@ function loadChunkAsync(
const chunkModules: CompressedModuleFactories = require(resolved)
installCompressedModuleFactories(chunkModules, 0, moduleFactories)
entry = loadedChunk
} catch (e) {
} catch (cause) {
const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`
const error = new Error(errorMessage, { cause })
error.name = 'ChunkLoadError'
// Cache the failure promise, future requests will also get this same rejection
entry = Promise.reject(
new Error(errorMessage, {
cause: e,
})
)
entry = Promise.reject(error)
}
chunkCache.set(chunkPath, entry)
}
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="683a00e2-39b4-f14a-ae2f-75a281be4c75")}catch(e){}}();
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="7c27d976-6b5b-3db4-da57-497b206bb98c")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -618,7 +618,7 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
let entry = instrumentedBackendLoadChunks.get(thenable);
if (entry === undefined) {
const resolve = instrumentedBackendLoadChunks.set.bind(instrumentedBackendLoadChunks, thenable, loadedChunk);
entry = thenable.then(resolve).catch((error)=>{
entry = thenable.then(resolve).catch((cause)=>{
let loadReason;
switch(sourceType){
case 0:
......@@ -633,9 +633,11 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? {
cause: error
let error = new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${cause ? `: ${cause}` : ''}`, cause ? {
cause
} : undefined);
error.name = 'ChunkLoadError';
throw error;
});
instrumentedBackendLoadChunks.set(thenable, entry);
}
......@@ -1835,5 +1837,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=683a00e2-39b4-f14a-ae2f-75a281be4c75
//# debugId=7c27d976-6b5b-3db4-da57-497b206bb98c
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -628,14 +628,16 @@ function loadRuntimeChunkPath(sourcePath, chunkPath) {
const chunkModules = require(resolved);
installCompressedModuleFactories(chunkModules, 0, moduleFactories);
loadedChunks.add(chunkPath);
} catch (e) {
} catch (cause) {
let errorMessage = `Failed to load chunk ${chunkPath}`;
if (sourcePath) {
errorMessage += ` from runtime for chunk ${sourcePath}`;
}
throw new Error(errorMessage, {
cause: e
const error = new Error(errorMessage, {
cause
});
error.name = 'ChunkLoadError';
throw error;
}
}
function loadChunkAsync(chunkData) {
......@@ -655,12 +657,14 @@ function loadChunkAsync(chunkData) {
const chunkModules = require(resolved);
installCompressedModuleFactories(chunkModules, 0, moduleFactories);
entry = loadedChunk;
} catch (e) {
} catch (cause) {
const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`;
const error = new Error(errorMessage, {
cause
});
error.name = 'ChunkLoadError';
// Cache the failure promise, future requests will also get this same rejection
entry = Promise.reject(new Error(errorMessage, {
cause: e
}));
entry = Promise.reject(error);
}
chunkCache.set(chunkPath, entry);
}
......
......@@ -628,14 +628,16 @@ function loadRuntimeChunkPath(sourcePath, chunkPath) {
const chunkModules = require(resolved);
installCompressedModuleFactories(chunkModules, 0, moduleFactories);
loadedChunks.add(chunkPath);
} catch (e) {
} catch (cause) {
let errorMessage = `Failed to load chunk ${chunkPath}`;
if (sourcePath) {
errorMessage += ` from runtime for chunk ${sourcePath}`;
}
throw new Error(errorMessage, {
cause: e
const error = new Error(errorMessage, {
cause
});
error.name = 'ChunkLoadError';
throw error;
}
}
function loadChunkAsync(chunkData) {
......@@ -655,12 +657,14 @@ function loadChunkAsync(chunkData) {
const chunkModules = require(resolved);
installCompressedModuleFactories(chunkModules, 0, moduleFactories);
entry = loadedChunk;
} catch (e) {
} catch (cause) {
const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`;
const error = new Error(errorMessage, {
cause
});
error.name = 'ChunkLoadError';
// Cache the failure promise, future requests will also get this same rejection
entry = Promise.reject(new Error(errorMessage, {
cause: e
}));
entry = Promise.reject(error);
}
chunkCache.set(chunkPath, entry);
}
......
......@@ -617,7 +617,7 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
let entry = instrumentedBackendLoadChunks.get(thenable);
if (entry === undefined) {
const resolve = instrumentedBackendLoadChunks.set.bind(instrumentedBackendLoadChunks, thenable, loadedChunk);
entry = thenable.then(resolve).catch((error)=>{
entry = thenable.then(resolve).catch((cause)=>{
let loadReason;
switch(sourceType){
case 0:
......@@ -632,9 +632,11 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? {
cause: error
let error = new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${cause ? `: ${cause}` : ''}`, cause ? {
cause
} : undefined);
error.name = 'ChunkLoadError';
throw error;
});
instrumentedBackendLoadChunks.set(thenable, entry);
}
......
......@@ -1096,7 +1096,7 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
var entry = instrumentedBackendLoadChunks.get(thenable);
if (entry === undefined) {
var resolve = instrumentedBackendLoadChunks.set.bind(instrumentedBackendLoadChunks, thenable, loadedChunk);
entry = thenable.then(resolve).catch(function(error) {
entry = thenable.then(resolve).catch(function(cause) {
var loadReason;
switch(sourceType){
case 0:
......@@ -1113,9 +1113,11 @@ function loadChunkByUrlInternal(sourceType, sourceData, chunkUrl) {
return `Unknown source type: ${sourceType}`;
});
}
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ''}`, error ? {
cause: error
var error = new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${cause ? `: ${cause}` : ''}`, cause ? {
cause: cause
} : undefined);
error.name = 'ChunkLoadError';
throw error;
});
instrumentedBackendLoadChunks.set(thenable, entry);
}
......
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