Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However I cannot get to those errors anyhow..


2 Answers

ref: https://v3.nuxtjs.org/api/composables/use-fetch useFetch return values {data, pending, error, refresh}, here is an example.

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('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)
})
like image 186
Aborn Jiang Avatar answered Jul 19 '26 21:07

Aborn Jiang


As @Aborn Jiang stated, useFetch returns a Promise. The resolved error-property is a ref.

You could access the error details in Nuxt3 like this:

const { error, data } = await useFetch('https://example.app/api/contact', {...});

console.log(error.value.data);
// Might be interesting as well:
console.log(error.value.name, error.value.message);
like image 45
floriankapaun Avatar answered Jul 19 '26 21:07

floriankapaun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!