【问题标题】:Handling errors on nuxt3 usefetch处理 nuxt3 usefetch 上的错误
【发布时间】:2023-02-04 14:34:45
【问题描述】:

我只是不知道如何在这里处理错误:

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)

在错误本身上,它返回带有 _error 的 ref,其中包含有错误的对象。但是无论如何我都无法解决这些错误..

【问题讨论】:

  • 试过try/catch

标签: vue.js nuxt.js vuejs3 nuxtjs3


【解决方案1】:

参考: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']
  }
)

顺便说一句,useFetch 返回一个承诺,在您的示例中,您可以执行以下操作。

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)
})

【讨论】:

    【解决方案2】:

    好的,这是一个实用的解决方案,您可以在检查错误后进行控制台日志,如下所示:

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

    你没有得到错误out,为什么console.log失败,需要获取值。

    【讨论】:

    • 我很难理解这个措辞“你没有得到错误,为什么 console.log 失败,你需要获得价值。”。请检查清晰度和可读性。
    猜你喜欢
    • 2022-08-09
    • 2022-11-10
    • 2022-08-19
    • 2022-11-11
    • 2022-07-21
    • 2022-12-30
    • 2022-11-11
    • 2022-01-11
    • 2011-10-02
    相关资源
    最近更新 更多