vuejs / core

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
https://vuejs.org/
MIT License
47.52k stars 8.31k forks source link

renderToString not throwing error from onServerPrefetch #9076

Open dmtkpv opened 1 year ago

dmtkpv commented 1 year ago

Vue version

3.3.4

Link to minimal reproduction

import { h, createApp, onServerPrefetch } from 'vue'
import { renderToString } from 'vue/server-renderer'

const Child = {
    render() {
        return h('span')
    },
    setup() {
        onServerPrefetch(async () => {
            throw new Error('An error')
        })
    }
}

const app = createApp({
    render () {
        return h('div', h(Child))
    }
})

try {
    await renderToString(app)
}
catch (e) {
    console.log(e.message);
}

Steps to reproduce

Run the script

What is expected?

The output is An error

What is actually happening?

file:///.../issue.js:10
            throw new Error('An error')
                  ^

Error: An error
    at file:///.../issue.js:10:19
    at /.../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:2669:88
    at callWithErrorHandling (/.../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:156:18)
    at callWithAsyncErrorHandling (/.../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:164:17)
    at hook.__weh.hook.__weh (/.../node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:2649:19)
    at /.../node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:625:65
    at Array.map (<anonymous>)
    at /.../node_modules/@vue/server-renderer/dist/server-renderer.cjs.js:625:38

System Info

No response

Any additional comments?

No response

EsunR commented 11 months ago

It will cause my server code to crash, I need to write a wrapper function to use it, like:

export function safeOnServerPrefetch(fn: () => any) {
    onServerPrefetch(async () => {
        try {
            await fn();
        } catch (e) {
            console.log('Running onServerPrefetch error:', e);
        }
    });
}
mikahozz commented 1 month ago

I'm experiencing this same issue. I'm actually trying to throw a custom Error from OnServerPrefetch and stop the execution of the component immediately. But it's impossible since Vue/Node will crash in a somewhat random spot even though I have try-catch on higher levels. The "random" crash place seems to be around executing: let template = await fs.readFile(path.resolve(__dirname, templateName), 'utf-8');