Backtestsvuerun-20261003-231210#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 A = our agent, Patch B = the merged fix.
Both patches fix the same root cause. When a component's async setup rejects, SSR still runs its `ssrRender`, and the resulting TypeError was never passed to `handleError`, so `onErrorCaptured` and `app.config.errorHandler` never saw it. Both add a catch around `ssrRender` that calls `handleError(err, instance, ErrorCodes.RENDER_FUNCTION)`. They differ in how they handle the edge cases. Patch B calls `handleError` unconditionally. In production with no handler, `logError` only does `console.error` (unless `throwUnhandledErrorInProduction` is set). So an unhandled render error that used to reject `renderToString` would now be logged and the render would continue with a partial buffer. That silently changes SSR failure behaviour. Patch B's guard against double reporting only wraps `renderComponentSubTree`. A synchronous setup error from `setupComponent`, which `handleError` re-throws in dev when unhandled, still propagates synchronously into the parent's compiled `ssrRender` catch. There it is reported a second time as a render-function error. Patch B also keeps whatever partial markup the failed component pushed before throwing. Its new test wraps the child in `<Suspense>` and expects the whole output to be `''`, which is an odd assertion that doesn't model the issue's parent and child layout well. Patch A makes three choices that avoid these problems: - It only swallows the error when an error handler actually exists (an app `errorHandler` or an ancestor `ec`). Otherwise it re-throws, so the existing rejection behaviour is kept. - It discards the partial buffer and emits `<!---->`, matching the client's `renderComponentRoot` behaviour. - It tracks a propagating error across nested synchronous `ssrRender` calls, so child setup or render errors already reported are not reported again by compiled ancestors. Patch A's tests cover: - async and sync setup errors followed by a template reading missing state, with the exact output and both captured errors asserted; - forwarding to `errorHandler`, with the partial output replaced; - unhandled render errors still rejecting and being reported exactly once; - child setup errors not being re-reported as render errors. The module-level depth and state tracking is a bit unusual, but it is limited to synchronous execution and reset in `finally`. Overall, Patch A is more correct on the edge cases the fix touches and is 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
14m 13s
Wall-clock time in the container
Full test suite
No new failures
3,626 passed · 6 skipped · 3,632 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
181vs 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/server-renderer/__tests__/render.spec.tsindex 268c7dc1e..5fb4fdb7b 100644@@ -944,6 +944,140 @@ function testRender(type: string, render: typeof renderToString) { expect(fn2).toBeCalledWith('async child error') }) + describe('render errors after setup errors', () => {+ const createParent = (Child: any, captured: unknown[]) =>+ createApp({+ components: { Child },+ setup() {+ const error = ref<unknown>(null)+ onErrorCaptured(e => {+ captured.push(e)+ error.value = e+ return false+ })+ return { error }+ },+ template: `<div class="app"><p v-if="error">error</p><Child v-else /></div>`,+ })++ test('async setup throws, template reads missing state', async () => {+ const captured: unknown[] = []+ const Child = defineComponent({+ async setup() {+ await new Promise(r => setTimeout(r, 10))+ throw new Error('async setup error')+ },+ template: `<div>{{ data.foo }}</div>`,+ })++ const html = await render(createParent(Child, captured))+ expect(html).toBe(`<div class="app"><!----></div>`)+ expect(captured.length).toBe(2)+ expect((captured[0] as Error).message).toBe('async setup error')+ expect(captured[1]).toBeInstanceOf(TypeError)+ expect(+ 'Property "data" was accessed during render but is not defined',+ ).toHaveBeenWarned()+ })++ test('sync setup throws, template reads missing state', async () => {+ const captured: unknown[] = []+ const Child = defineComponent({+ setup() {+ throw new Error('sync setup error')+ },+ template: `<div>{{ data.foo }}</div>`,+ })++ const html = await render(createParent(Child, captured))+ expect(html).toBe(`<div class="app"><!----></div>`)+ expect(captured.length).toBe(2)+ expect((captured[0] as Error).message).toBe('sync setup error')+ expect(captured[1]).toBeInstanceOf(TypeError)+ expect(+ 'Property "data" was accessed during render but is not defined',+ ).toHaveBeenWarned()+ })++ test('ssrRender error is passed to app.config.errorHandler', async () => {+ const handler = vi.fn()+ const Child = {+ ssrRender(_ctx: any, push: any) {+ push(`<div><span>partial`)+ throw new Error('render error')+ },+ }+ const app = createApp({+ components: { Child },+ template: `<div class="app"><Child /><b>after</b></div>`,+ })+ app.config.errorHandler = handler++ const html = await render(app)+ expect(html).toBe(`<div class="app"><!----><b>after</b></div>`)+ expect(handler).toHaveBeenCalledTimes(1)+ expect(handler.mock.calls[0][0].message).toBe('render error')+ expect(handler.mock.calls[0][2]).toBe('render function')+ })++ test('unhandled ssrRender error still rejects and is reported once', async () => {+ const errorCaptured = vi.fn()+ const err = new Error('unhandled render error')+ const Child = {+ ssrRender() {+ throw err+ },+ }+ const Mid = {+ components: { Child },+ template: `<section><Child /></section>`,+ }+ const app = createApp({+ components: { Mid },+ errorCaptured,+ template: `<div><Mid /></div>`,+ })++ // stream renderers throw synchronously for sync render errors+ await expect((async () => render(app))()).rejects.toBeDefined()+ expect(errorCaptured).toHaveBeenCalledTimes(1)+ expect(errorCaptured.mock.calls[0][0]).toBe(err)+ expect(+ 'Unhandled error during execution of render function',+ ).toHaveBeenWarnedTimes(1)+ })++ test('setup error of a child is not re-reported by compiled parent', async () => {+ const errorCaptured = vi.fn()+ const err = new Error('child setup error')+ const Child = {+ setup() {+ throw err+ },+ template: `<div>child</div>`,+ }+ const Mid = {+ components: { Child },+ template: `<section><Child /></section>`,+ }+ const app = createApp({+ components: { Mid },+ errorCaptured,+ template: `<div><Mid /></div>`,+ })++ await expect((async () => render(app))()).rejects.toBe(err)+ expect(errorCaptured).toHaveBeenCalledTimes(1)+ expect(errorCaptured.mock.calls[0][2]).toBe('setup function')+ expect(+ 'Unhandled error during execution of setup function',+ ).toHaveBeenWarnedTimes(1)+ expect(+ 'Unhandled error during execution of render function',+ ).not.toHaveBeenWarned()+ })+ })+ // https://github.com/vuejs/core/issues/3322 test('effect onInvalidate does not error', async () => { const noop = () => {}packages/server-renderer/src/render.tsindex 8fc9b0128..d1c113ff1 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,@@ -40,6 +42,14 @@ const { popWarningContext, } = ssrUtils +// An error escaping a nested component (e.g. its setup or render error was+// already reported via handleError and re-thrown, or deliberately left+// unhandled) is propagating through enclosing synchronous ssrRender calls.+// The enclosing components must not report it again.+const NO_ERROR = {}+let propagatingRenderError: unknown = NO_ERROR+let ssrRenderDepth = 0+ export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean } export type SSRBufferItem = string | SSRBuffer | Promise<SSRBuffer> export type PushFn = (item: SSRBufferItem) => void@@ -93,6 +103,19 @@ export function renderComponentVNode( vnode: VNode, parentComponent: ComponentInternalInstance | null = null, slotScopeId?: string,+): SSRBuffer | Promise<SSRBuffer> {+ try {+ return doRenderComponentVNode(vnode, parentComponent, slotScopeId)+ } catch (err) {+ if (ssrRenderDepth > 0) propagatingRenderError = err+ throw err+ }+}++function doRenderComponentVNode(+ vnode: VNode,+ parentComponent: ComponentInternalInstance | null,+ slotScopeId?: string, ): SSRBuffer | Promise<SSRBuffer> { const instance = (vnode.component = createComponentInstance( vnode,@@ -129,7 +152,7 @@ function renderComponentSubTree( ): SSRBuffer | Promise<SSRBuffer> { if (__DEV__) pushWarningContext(instance.vnode) const comp = instance.type as Component- const { getBuffer, push } = createBuffer()+ let { getBuffer, push } = createBuffer() if (isFunction(comp)) { let root = renderComponentRoot(instance) // #5817 scope ID attrs not falling through if functional component doesn't@@ -189,6 +212,7 @@ function renderComponentSubTree( // set current rendering instance for asset resolution const prev = setCurrentRenderingInstance(instance)+ ssrRenderDepth++ try { ssrRender( instance.proxy,@@ -201,7 +225,18 @@ function renderComponentSubTree( instance.data, instance.ctx, )+ } catch (err) {+ if (err === propagatingRenderError || !hasErrorHandler(instance)) {+ throw err+ }+ // same as renderComponentRoot on the client: report the error to+ // errorCaptured hooks / app errorHandler and render a comment in place+ // of the (possibly partial) output of this component+ ;({ getBuffer, push } = createBuffer())+ handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+ push(`<!---->`) } finally {+ if (--ssrRenderDepth === 0) propagatingRenderError = NO_ERROR setCurrentRenderingInstance(prev) } } else if (instance.render && instance.render !== NOOP) {@@ -221,6 +256,16 @@ function renderComponentSubTree( return getBuffer() } +function hasErrorHandler(instance: ComponentInternalInstance): boolean {+ if (instance.appContext.config.errorHandler) return true+ let cur = instance.parent+ while (cur) {+ if (cur.ec) return true+ cur = cur.parent+ }+ return false+}+ export function renderVNode( push: PushFn, vnode: VNode,
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) }