简体   繁体   English

处理 nuxt3 usefetch 上的错误

[英]Handling errors on nuxt3 usefetch

I just cant figure out how to handle errors here:我只是不知道如何处理这里的错误:

const { error, data } = useFetch('https://example.app/api/contact', {
   method: "POST",
   headers: { "Content-Type": "application/json" },
   body: {
      name: form.name.value,
      email: form.email.value,
      message: form.message.value
   }
});
console.log(error.value, error)

On error itself it returns ref with _error that contains object with errors.在错误本身上,它返回带有 _error 的 ref,其中包含 object 错误。 However I cannot get to those errors anyhow..但是无论如何我都无法解决这些错误..

ref: https://v3.nuxtjs.org/api/composables/use-fetch useFetch return values {data, pending, error, refresh}, here is an example. ref: https://v3.nuxtjs.org/api/composables/use-fetch useFetch 返回值 {data, pending, error, refresh},这里是一个例子。

 const { data, pending, error, refresh } = await useFetch( 'https://api.nuxtjs.dev/mountains', { pick: ['title'] } )

BTW,useFetch return a Promise , in your example, you can do as follows.顺便说一句,useFetch 返回一个Promise ,在您的示例中,您可以执行以下操作。

 useFetch('https://example.app/api/contact', { method: "POST", headers: { "Content-Type": "application/json" }, body: { name: form.name.value, email: form.email.value, message: form.message.value } }).then(res => { const data = res.data.value const error = res.error.value if (error) { // dealing error console.log(error) } else { console.log(data) } }, error => { console.log('exception...') console.log(error) })

Ok, here is a practical solution, you can do the console log after checking error, like this:好的,这是一个实用的解决方案,您可以在检查错误后进行控制台日志,如下所示:

if (error.value) {
  console.log(error.value)
  throw createError({statusCode: 404, statusMessage: "Page 
 not found.", fatal: true})     
 } 

You do not get error out, why console.log fails, you need to get the value after the error is trigged.你没有得到错误,为什么 console.log 失败,你需要在触发错误后获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM