Backtestsvuerun-20261013-093701#12575
Vue is not catching errors on server side in SSR when using async child setup
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
In SSR, a rejected async setup is already passed to handleError, so onErrorCaptured does fire for the setup error. The real failure is what happens next: the server renderer still renders the component with incomplete state, and the resulting TypeError crashes the whole renderToString. Patch B fixes this at that point. The setup promise's catch now rethrows after handleError, so the server renderer knows setup failed. renderComponentVNode records the failure, skips serverPrefetch hooks for the broken instance, and renders through renderComponentSubTreeAfterSetupError. Any render error there goes through handleError (RENDER_FUNCTION), so errorCaptured and app.config.errorHandler see it. The component's local buffer is discarded and replaced with a `<!---->` placeholder, which avoids partial or corrupted HTML. Siblings keep rendering, matching how the client handles render errors. Patch B also moves popWarningContext into a finally block so warning context stays balanced on throw. Patch B's tests cover: - the template path with errorCaptured and a sibling; - the compiled ssrRender path, explicitly checking that partial output is discarded; - serverPrefetch not running after setup rejects. These tests would fail before the change. Patch A wraps every ssrRender call in a catch that calls handleError, for all components, not just ones whose async setup failed. This is a broad behavior change. In production, handleError only logs, so any SSR render error anywhere is now swallowed. The partially pushed content stays in the buffer, which can produce malformed HTML instead of rejecting the render. The change needed edits to existing tests (new warning expectations) and a Promise.reject wrapper to avoid double handling, which shows how much it shifts error semantics. Patch A also does not stop serverPrefetch hooks running on an instance whose setup failed, and its single new test depends on Suspense. Patch B is more precise, lower risk, and better tested.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
8m 42s
Wall-clock time in the container
Full test suite
No new failures
1,735 passed · 1 skipped · 1,736 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
153vs 58 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.13
Link to minimal reproduction
Steps to reproduce
Just open a link and you will see errors when SSR is ON.
When SSR is OFF everything works as expected.
Also, commeting the line with top-level await (making Comp.vue a sync component) will also work fine both with and without SSR.
What is expected?
In SSR mode the page is expected to be blank white for 1 second and then display error message from App.vue.
This works as expected with SSR turned off.
Basically onErrorCaptured should be triggered, child setup and <template> render immediately stopped and error message from parent component shown.
What is actually happening?
In SSR mode the page is blank for 1 second but then it tries to render the <template> of Comp.vue using the data that might not even exist (because it appears in setup after throwing error).
And even if it manages to render <template> correctly, it still does not trigger onErrorCaptured in App.vue and do not switch to show error message.
Any additional comments?
I am building a custom rendering package built on top of Vue and it heavily uses structures like these:
// Wrappers are supposed to catch ALL errors and throws in child <Block /> and show nice error message
<BlockWrapper>
<Block ... />
</BlockWrapper>
<BlockWrapper>
<Block ... />
</BlockWrapper>
<BlockWrapper>
<Block ... />
</BlockWrapper>
...
Because of this bug OR my misunderstanding of how to handle async errors in Vue 3, even when thrown it still tries to render child block's <template> even with missing data (because setup is stopped executing), throws on reading properties of non-existing objects and the whole Nuxt page breaks.
Please, don't tell me this is a no-fix. It would be a disaster... 😭
The two patches
packages/runtime-core/src/component.tsindex c46741bee..0e076c733 100644@@ -898,6 +898,9 @@ function setupStatefulComponent( }) .catch(e => { handleError(e, instance, ErrorCodes.SETUP_FUNCTION)+ // keep the promise rejected so the server renderer knows setup+ // did not complete and the component state may be incomplete+ throw e }) } else if (__FEATURE_SUSPENSE__) { // async setup returned Promise.packages/server-renderer/__tests__/render.spec.tsindex 268c7dc1e..a47f6a2a0 100644@@ -944,6 +944,93 @@ function testRender(type: string, render: typeof renderToString) { expect(fn2).toBeCalledWith('async child error') }) + // #12575+ test('error handling w/ async setup should not crash rendering of incomplete state', async () => {+ const errors: unknown[] = []+ const infos: string[] = []++ const AsyncChild = defineComponent({+ async setup() {+ await new Promise(r => setTimeout(r))+ throw new Error('async setup error')+ // eslint-disable-next-line no-unreachable+ return { data: { msg: 'hello' } }+ },+ template: `<div>{{ data.msg }}</div>`,+ })+ const app = createApp({+ components: { AsyncChild },+ template: `<div class="app"><AsyncChild /><span>sibling</span></div>`,+ errorCaptured(err: unknown, _instance: unknown, info: string) {+ errors.push(err)+ infos.push(info)+ return false+ },+ })++ const html = await render(app)+ expect(html).toBe(`<div class="app"><!----><span>sibling</span></div>`)+ expect(errors.length).toBe(2)+ expect((errors[0] as Error).message).toBe('async setup error')+ expect(errors[1]).toBeInstanceOf(TypeError)+ expect(infos).toEqual(['setup function', 'render function'])+ expect('Property "data" was accessed during render').toHaveBeenWarned()+ })++ // #12575+ test('error handling w/ async setup and compiled ssrRender', async () => {+ const errorHandler = vi.fn()++ const AsyncChild = defineComponent({+ async setup() {+ await Promise.resolve()+ throw new Error('async setup error')+ },+ ssrRender(_ctx: any, _push: any) {+ _push(`<div>`)+ _push(String(_ctx.data.msg))+ _push(`</div>`)+ },+ })+ const app = createApp({+ render: () => h('div', { class: 'app' }, [h(AsyncChild)]),+ })+ app.config.errorHandler = errorHandler++ const html = await render(app)+ // partial output of the failed render must be discarded+ expect(html).toBe(`<div class="app"><!----></div>`)+ expect(errorHandler).toHaveBeenCalledTimes(2)+ expect(errorHandler.mock.calls[0][0].message).toBe('async setup error')+ expect(errorHandler.mock.calls[0][2]).toBe('setup function')+ expect(errorHandler.mock.calls[1][0]).toBeInstanceOf(TypeError)+ expect(errorHandler.mock.calls[1][2]).toBe('render function')+ expect('Property "data" was accessed during render').toHaveBeenWarned()+ })++ // #12575+ test('should not run serverPrefetch after async setup rejects', async () => {+ const prefetch = vi.fn()+ const errorHandler = vi.fn()++ const AsyncChild = defineComponent({+ async setup() {+ onServerPrefetch(prefetch)+ await Promise.resolve()+ throw new Error('async setup error')+ },+ template: `<div>child</div>`,+ })+ const app = createApp({+ render: () => h(AsyncChild),+ })+ app.config.errorHandler = errorHandler++ expect(await render(app)).toBe(`<div>child</div>`)+ expect(errorHandler).toHaveBeenCalledTimes(1)+ expect(prefetch).not.toHaveBeenCalled()+ })+ // https://github.com/vuejs/core/issues/3322 test('effect onInvalidate does not error', async () => { const noop = () => {}packages/server-renderer/src/render.tsindex 8fc9b0128..bccffc0a9 100644@@ -3,6 +3,7 @@ import { type Component, type ComponentInternalInstance, type DirectiveBinding,+ ErrorCodes, Fragment, type FunctionalComponent, Static,@@ -10,6 +11,7 @@ import { type VNode, type VNodeArrayChildren, type VNodeProps,+ handleError, mergeProps, ssrUtils, warn,@@ -105,29 +107,69 @@ export function renderComponentVNode( const hasAsyncSetup = isPromise(res) let prefetches = instance.sp /* LifecycleHooks.SERVER_PREFETCH */ if (hasAsyncSetup || prefetches) {+ let setupFailed = false const p: Promise<unknown> = Promise.resolve(res as Promise<void>)- .then(() => {- // instance.sp may be null until an async setup resolves, so evaluate it here- if (hasAsyncSetup) prefetches = instance.sp- if (prefetches) {- return Promise.all(- prefetches.map(prefetch => prefetch.call(instance.proxy)),- )- }- })+ .then(+ () => {+ // instance.sp may be null until an async setup resolves, so evaluate it here+ if (hasAsyncSetup) prefetches = instance.sp+ if (prefetches) {+ return Promise.all(+ prefetches.map(prefetch => prefetch.call(instance.proxy)),+ )+ }+ },+ () => {+ // async setup rejected. The error has already been passed to+ // handleError() in setupStatefulComponent().+ setupFailed = true+ },+ ) // Note: error display is already done by the wrapped lifecycle hook function. .catch(NOOP)- return p.then(() => renderComponentSubTree(instance, slotScopeId))+ return p.then(() =>+ setupFailed+ ? renderComponentSubTreeAfterSetupError(instance, slotScopeId)+ : renderComponentSubTree(instance, slotScopeId),+ ) } else { return renderComponentSubTree(instance, slotScopeId) } } +// #12575 when async setup rejects, the component's state is incomplete and+// its render may throw. Route such errors through the error handling chain+// (errorCaptured / app.config.errorHandler) and render a placeholder, the same+// way the client renderer handles render errors, instead of failing the whole+// SSR render.+function renderComponentSubTreeAfterSetupError(+ instance: ComponentInternalInstance,+ slotScopeId?: string,+): SSRBuffer | Promise<SSRBuffer> {+ try {+ return renderComponentSubTree(instance, slotScopeId)+ } catch (err) {+ handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+ return [`<!---->`]+ }+}+ function renderComponentSubTree( instance: ComponentInternalInstance, slotScopeId?: string, ): SSRBuffer | Promise<SSRBuffer> { if (__DEV__) pushWarningContext(instance.vnode)+ try {+ return doRenderComponentSubTree(instance, slotScopeId)+ } finally {+ if (__DEV__) popWarningContext()+ }+}++function doRenderComponentSubTree(+ instance: ComponentInternalInstance,+ slotScopeId?: string,+): SSRBuffer { const comp = instance.type as Component const { getBuffer, push } = createBuffer() if (isFunction(comp)) {@@ -217,7 +259,6 @@ function renderComponentSubTree( push(`<!---->`) } }- if (__DEV__) popWarningContext() return getBuffer() }
packages/server-renderer/__tests__/render.spec.tsindex 268c7dc1e..f537a6219 100644@@ -12,6 +12,7 @@ import { defineComponent, getCurrentInstance, h,+ nextTick, onErrorCaptured, onServerPrefetch, reactive,@@ -822,6 +823,9 @@ function testRender(type: string, render: typeof renderToString) { ) } catch {} expect(getCurrentInstance()).toBe(prev)+ expect(+ '[Vue warn]: Unhandled error during execution of render function',+ ).toHaveBeenWarned() }) // #7733@@ -1191,6 +1195,40 @@ function testRender(type: string, render: typeof renderToString) { expect((capturedError as unknown as Error).message).toBe('An error') }) + test('async setup throwing error', async () => {+ const capturedError: string[] = []++ const Child = {+ async setup() {+ await nextTick()+ throw new Error('An error')+ return { foo: { bar: 1 } }+ },+ template: `<span>{{ foo.bar }}</span>`,+ }++ const app = createApp({+ components: { Child },+ setup() {+ onErrorCaptured(e => {+ capturedError.push(e.message)+ return false+ })+ },+ template: `<Suspense><Child /></Suspense>`,+ })++ expect(await render(app)).toBe('')+ expect(capturedError.length).toBe(2)+ expect(capturedError).toStrictEqual([+ 'An error',+ "Cannot read properties of undefined (reading 'bar')",+ ])+ expect(+ '[Vue warn]: Property "foo" was accessed during render but is not defined on instance',+ ).toHaveBeenWarned()+ })+ test('computed reactivity during SSR with onServerPrefetch', async () => { const store = { // initial state could be hydratedpackages/server-renderer/__tests__/ssrSuspense.spec.tsindex 5f8cecaf9..2cc3da1cd 100644@@ -107,9 +107,10 @@ describe('SSR Suspense', () => { // nuxt/nuxt#28162 test('propagates sync errors from compiled ssrRenderSuspense default slot', async () => {+ const error = new TypeError('bang') const Throwing = defineComponent({ ssrRender(_ctx: any, _push: any) {- throw new TypeError('bang')+ throw error }, }) @@ -124,7 +125,10 @@ describe('SSR Suspense', () => { }, }) - await expect(renderToString(createApp(Root))).rejects.toThrow('bang')+ await expect(renderToString(createApp(Root))).rejects.toBe(error)+ expect(+ '[Vue warn]: Unhandled error during execution of render function',+ ).toHaveBeenWarnedTimes(1) }) test('passing suspense in failing suspense', async () => {packages/server-renderer/src/render.tsindex 8fc9b0128..c2bde4d1e 100644@@ -3,6 +3,7 @@ import { type Component, type ComponentInternalInstance, type DirectiveBinding,+ ErrorCodes, Fragment, type FunctionalComponent, Static,@@ -10,6 +11,7 @@ import { type VNode, type VNodeArrayChildren, type VNodeProps,+ handleError, mergeProps, ssrUtils, warn,@@ -119,7 +121,13 @@ export function renderComponentVNode( .catch(NOOP) return p.then(() => renderComponentSubTree(instance, slotScopeId)) } else {- return renderComponentSubTree(instance, slotScopeId)+ try {+ return renderComponentSubTree(instance, slotScopeId)+ } catch (err) {+ // let the SSR buffer propagate the error so parent render functions+ // don't handle the same error again+ return Promise.reject(err)+ } } } @@ -201,6 +209,8 @@ function renderComponentSubTree( instance.data, instance.ctx, )+ } catch (err) {+ handleError(err, instance, ErrorCodes.RENDER_FUNCTION) } finally { setCurrentRenderingInstance(prev) }