Backtestsvuerun-20261002-115633#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.
Patch B targets the actual failure mode. When an async setup rejects during SSR, the instance's render context is incomplete. Patch B makes the SSR-only setup promise rethrow after `handleError`, so the server renderer knows setup failed. Only in that case does it render into a separate buffer, send render errors through `handleError` with RENDER_FUNCTION (so they reach `errorCaptured` / `app.config.errorHandler`), and emit a `<!---->` placeholder instead of partial output. This matches the client behavior the issue expects: the parent captures the error and the broken child's template is not emitted. Its tests are thorough and would fail before the change. They cover propagation to the parent `errorCaptured`, to the app `errorHandler`, compiled `ssrRender`, and the unhandled case. They also check that sibling output is preserved and the failed child's partial HTML is discarded. Patch A takes a broader, riskier approach. It wraps every component's `ssrRender` in `handleError` and turns synchronous throws into `Promise.reject` for every SSR component, not just failed async setups. That changes global SSR error semantics and required changing existing tests. When an `errorCaptured` hook returns false, rendering continues with whatever was already pushed to the buffer. Any partially emitted markup (for example an opened `<p>` before the throwing expression) leaks into the output as malformed HTML. Its single new test passes only because the error happens before anything is pushed. Patch A also does not tell the renderer that setup failed, so it cannot discard partial output. Patch B's fix is narrower in effect, more robust to partial output, 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
13m 14s
Wall-clock time in the container
Full test suite
No new failures
3,623 passed · 6 skipped · 3,629 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
163vs 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..fbea7a8c4 100644@@ -898,6 +898,9 @@ function setupStatefulComponent( }) .catch(e => { handleError(e, instance, ErrorCodes.SETUP_FUNCTION)+ // re-throw so the server renderer knows setup did not complete+ // and can handle errors from rendering the incomplete instance+ throw e }) } else if (__FEATURE_SUSPENSE__) { // async setup returned Promise.packages/server-renderer/__tests__/render.spec.tsindex 268c7dc1e..878d4f872 100644@@ -869,6 +869,104 @@ function testRender(type: string, render: typeof renderToString) { expect(getCurrentInstance()).toBe(null) }) + // #12575+ describe('render error after async setup rejects', () => {+ afterEach(() => {+ expect(+ 'Property "data" was accessed during render but is not defined',+ ).toHaveBeenWarned()+ })++ // `data` would have been returned after the await, but setup throws+ const createFailingSetup = () =>+ async function setup() {+ await Promise.resolve()+ throw new Error('setup failed')+ }++ test('should be passed to parent errorCaptured', async () => {+ const Child = defineComponent({+ setup: createFailingSetup(),+ template: `<p><span>{{ data.msg }}</span></p>`,+ })+ const errors: unknown[] = []+ const app = createApp({+ setup() {+ onErrorCaptured(err => {+ errors.push(err)+ return false+ })+ return () => h('div', [h(Child), h('span', 'sibling')])+ },+ })+ const html = await render(app)+ // partial output of the failed child is discarded+ expect(html).toBe(`<div><!----><span>sibling</span></div>`)+ expect(errors.length).toBe(2)+ expect((errors[0] as Error).message).toBe('setup failed')+ expect(errors[1]).toBeInstanceOf(TypeError)+ })++ test('should be passed to app errorHandler', async () => {+ const Child = defineComponent({+ setup: createFailingSetup(),+ template: `<p>{{ data.msg }}</p>`,+ })+ const app = createApp({+ render: () => h('div', [h(Child), h('span', 'sibling')]),+ })+ const errorHandler = vi.fn()+ app.config.errorHandler = errorHandler+ const html = await render(app)+ expect(html).toBe(`<div><!----><span>sibling</span></div>`)+ expect(errorHandler).toHaveBeenCalledTimes(2)+ expect((errorHandler.mock.calls[0][0] as Error).message).toBe(+ 'setup failed',+ )+ expect(errorHandler.mock.calls[1][0]).toBeInstanceOf(TypeError)+ })++ test('should be handled for compiled ssrRender', async () => {+ const Child = defineComponent({+ setup: createFailingSetup(),+ ssrRender(ctx: any, push: any) {+ push(`<p>`)+ push(ctx.data.msg)+ push(`</p>`)+ },+ })+ const errors: unknown[] = []+ const app = createApp({+ errorCaptured(err) {+ errors.push(err)+ return false+ },+ render: () => h('div', [h(Child)]),+ })+ const html = await render(app)+ expect(html).toBe(`<div><!----></div>`)+ expect(errors.length).toBe(2)+ expect(errors[1]).toBeInstanceOf(TypeError)+ })++ test('should propagate when unhandled', async () => {+ const Child = defineComponent({+ setup: createFailingSetup(),+ template: `<p>{{ data.msg }}</p>`,+ })+ const app = createApp({+ render: () => h('div', [h(Child)]),+ })+ await expect(render(app)).rejects.toBeDefined()+ expect(+ 'Unhandled error during execution of setup function',+ ).toHaveBeenWarned()+ expect(+ 'Unhandled error during execution of render function',+ ).toHaveBeenWarned()+ })+ })+ test('serverPrefetch', async () => { const msg = Promise.resolve('hello') const app = createApp({packages/server-renderer/src/render.tsindex 8fc9b0128..3893a2c23 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,19 +107,30 @@ 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() by setupComponent(), but the render context may be+ // incomplete, so errors during rendering must be handled as well.+ 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(() =>+ renderComponentSubTree(instance, slotScopeId, setupFailed),+ ) } else { return renderComponentSubTree(instance, slotScopeId) }@@ -126,6 +139,7 @@ export function renderComponentVNode( function renderComponentSubTree( instance: ComponentInternalInstance, slotScopeId?: string,+ setupFailed = false, ): SSRBuffer | Promise<SSRBuffer> { if (__DEV__) pushWarningContext(instance.vnode) const comp = instance.type as Component@@ -187,12 +201,10 @@ function renderComponentSubTree( } } - // set current rendering instance for asset resolution- const prev = setCurrentRenderingInstance(instance)- try {+ const doRender = (pushFn: PushFn) => ssrRender( instance.proxy,- push,+ pushFn, instance, attrs, // compiler-optimized bindings@@ -201,6 +213,28 @@ function renderComponentSubTree( instance.data, instance.ctx, )++ // set current rendering instance for asset resolution+ const prev = setCurrentRenderingInstance(instance)+ try {+ if (setupFailed) {+ // async setup() rejected, so the render context may be incomplete.+ // Render into a separate buffer so that partial output can be+ // discarded, and - like renderComponentRoot() does for render+ // functions - pass render errors to handleError() (errorCaptured /+ // app.config.errorHandler) and render a placeholder comment instead.+ const sub = createBuffer()+ let rendered = false+ try {+ doRender(sub.push)+ rendered = true+ } catch (err) {+ handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+ }+ push(rendered ? sub.getBuffer() : `<!---->`)+ } else {+ doRender(push)+ } } finally { setCurrentRenderingInstance(prev) }
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) }