簡體   English   中英

處理 nuxt3 usefetch 上的錯誤

[英]Handling errors on nuxt3 usefetch

我只是不知道如何處理這里的錯誤:

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,其中包含 object 錯誤。 但是無論如何我都無法解決這些錯誤..

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

順便說一句,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) })

好的,這是一個實用的解決方案,您可以在檢查錯誤后進行控制台日志,如下所示:

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

你沒有得到錯誤,為什么 console.log 失敗,你需要在觸發錯誤后獲取值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM