Handling errors on nuxt3 usefetch
Asked Answered
S

4

7

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..

Skedaddle answered 1/4, 2022 at 22:44 Comment(1)
Tried a try/catch?Remonstrate
M
10

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)
})
Metsky answered 30/5, 2022 at 6:49 Comment(1)
second part is not working good (error => ...) but can be fixed to suit your needsSpool
K
2

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.

Keyhole answered 3/2, 2023 at 22:41 Comment(3)
I have trouble understanding this phrasing "You do not get error out, why console.log fails, you need to get the value.". Please review for clarity and readability.Durnan
The questioner have: console.log(error.value, error) The error will not be proceed, as it is an object, but error.value will. It is basic programming knowlage.Keyhole
Well, you get it, but it is not readable message. Nuxt is quite complicated. The thing is also if it is the server or the client who handle the error. If the server handle it, you need to do clearError(), to get console.log out. I just tried to explain it in an easy way.Keyhole
A
2

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);
Allister answered 4/4, 2023 at 6:22 Comment(0)
B
0

You can find your backend error response using console.log(error.value?.data) instead of console.log(error.value, error)

Here are some changes to your method:

const create = () => {
    try{
        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
            }
         });
         if(error.value) throw error.value;
    }catch(e){
        handleFetchError(e);
    }
}
const handleFetchError = (error: any) => {
    let errorMessage = 'Failed to send your message. Please try again';

    if (error.data && error.data.message) {
        errorMessage = Array.isArray(error.data.message)
            ? error.data.message.join(', ')
            : error.data.message;
    }
};
Bini answered 19/6 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.