From cf0cbf6a37a461f9040d456aa934d13aa7fb9617 Mon Sep 17 00:00:00 2001 From: vanaigr Date: Tue, 5 Nov 2024 05:25:29 -0600 Subject: [PATCH] fix(vite-node): top-level throw in module is not reported properly (#6840) Co-authored-by: Hiroshi Ogawa --- packages/vite-node/src/hmr/hmr.ts | 4 ++-- test/vite-node/src/hmr-throw.js | 11 +++++++++++ test/vite-node/test/hmr.test.ts | 13 +++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 test/vite-node/src/hmr-throw.js diff --git a/packages/vite-node/src/hmr/hmr.ts b/packages/vite-node/src/hmr/hmr.ts index 255218059b78..564ac22f4929 100644 --- a/packages/vite-node/src/hmr/hmr.ts +++ b/packages/vite-node/src/hmr/hmr.ts @@ -160,8 +160,8 @@ async function fetchUpdate( } } -function warnFailedFetch(err: Error, path: string | string[]) { - if (!err.message.match('fetch')) { +function warnFailedFetch(err: unknown, path: string | string[]) { + if (!(err instanceof Error) || !err.message.match('fetch')) { console.error(err) } diff --git a/test/vite-node/src/hmr-throw.js b/test/vite-node/src/hmr-throw.js new file mode 100644 index 000000000000..cdd53e74f2ae --- /dev/null +++ b/test/vite-node/src/hmr-throw.js @@ -0,0 +1,11 @@ +if (import.meta.hot) { + import.meta.hot.accept(() => {}) + if (import.meta.hot.data.value == null) { + import.meta.hot.data.value = 0 + } + else { + // eslint-disable-next-line no-throw-literal + throw 'some error' + } +} +console.error('ready') diff --git a/test/vite-node/test/hmr.test.ts b/test/vite-node/test/hmr.test.ts index b3b29712b542..f24d8a7d7865 100644 --- a/test/vite-node/test/hmr.test.ts +++ b/test/vite-node/test/hmr.test.ts @@ -15,3 +15,16 @@ test('hmr.accept works correctly', async () => { await viteNode.waitForStderr('Accept') await viteNode.waitForStdout(`[vite-node] hot updated: ${scriptFile}`) }) + +test('can handle top-level throw in self-accepting module', async () => { + const scriptFile = resolve(__dirname, '../src/hmr-throw.js') + + const { viteNode } = await runViteNodeCli('--watch', scriptFile) + + await viteNode.waitForStderr('ready') + + editFile(scriptFile, content => `${content}\nconsole.error("done")`) + + await viteNode.waitForStderr('some error') + await viteNode.waitForStderr(`[hmr] Failed to reload ${scriptFile}. This could be due to syntax errors or importing non-existent modules. (see errors above)`) +})