英文:
Handling error on a vue component render function
问题
以下是您提供的代码的中文翻译部分:
// 组件设置方法
/**
* 从表单对象中解析模型键
* @throws {Error}
*/
const resolveModel = () => {
const output = // 从表单对象中解析值
// 如果在表单对象中找不到值,抛出错误
if (typeof output === 'undefined') {
throw new Error(
`FormBuilder: 模型键 "${props.field.id}" 在表单对象中未找到`
)
}
// 返回已解析的值
return output
}
return () => h('Component', {
modelValue: resolveModel(), //<-- 如何处理这里抛出的异常?
})
我正在使用vitest,并且通过以下测试来验证是否抛出了错误。
it('如果模型值在表单对象中不存在,会抛出错误', async () => {
try {
await wrapper.setProps({
field: {
id: 'rental.vendor_id',
},
})
} catch (e) {
expect(e.message).toBe(
'FormBuilder: 模型键 "rental.vendor_id" 在表单对象中未找到'
)
}
})
上述测试通过了,但我仍然在控制台中收到两个警告:[Vue warn]: 在执行渲染函数时出现未处理的错误
和 [Vue warn]: 在执行调度程序刷新时出现未处理的错误。这很可能是Vue内部的错误。请在 https://new-issue.vuejs.org/?repo=vuejs/core 打开一个问题报告
有没有办法捕获此错误以抑制控制台警告?
英文:
I have a FormBuilder Vue component that uses the h render function; this component resolves the modelValue programmatically with a method resolveModel()
. This method throws an error if the modelValue is not found in the Form object.
// Component Setup Method
/**
* Resolve the model key from the form object
* @throws {Error}
*/
const resolveModel = () => {
const output = // Resolve value from the form object
// If no value was found in the form object, throw an error
if (typeof output === 'undefined') {
throw new Error(
`FormBuilder: Model key "${props.field.id}" not found in form object`
)
}
// Return the resolved value
return output
}
return () => h('Component', {
modelValue: resolveModel(), <-- How to handle exception thrown here?
})
I am using vitest, and I test that the error is thrown with the test below.
it('throws an error if the model value does not exist in the form object', async () => {
try {
await wrapper.setProps({
field: {
id: 'rental.vendor_id',
},
})
} catch (e) {
expect(e.message).toBe(
'FormBuilder: Model key "rental.vendor_id" not found in form object'
)
}
})
The above test passes but I still get two warnings in the console [Vue warn]: Unhandled error during execution of render function
and [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core
Any idea how to catch this error to suppress the console warnings?
答案1
得分: 0
你可以将你的渲染函数包裹在一个 try / catch 块中来处理异常。但你需要决定在这种情况下渲染什么。
return () => {
try {
return h('Component', {
modelValue: resolveModel(), <-- 如何处理此处抛出的异常?
})
} catch (renderError) {
// 处理异常,但必须返回一些内容以进行渲染
return h()
}
}
英文:
You can wrap your render function under a try / catch block to handle the exception. But you'll need to decide what to render in this case.
return () => {
try {
return h('Component', {
modelValue: resolveModel(), <-- How to handle exception thrown here?
})
} catch (renderError) {
// Handle the exception, but it has to return something to render
return h()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论