user16275964
user16275964

Reputation:

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

Upvotes: 7

Views: 28790

Answers (5)

Alper Aydingül
Alper Aydingül

Reputation: 261

const { params } = useRoute();
const { data, error } = await useFetch('/api/example/load', {
    method: 'POST',
    body: {
        id: params.id,
    },
});

if (error.value) {
    throw createError({
        statusCode: error.value.statusCode,
        statusMessage: error.value.data.statusMessage,
        fatal: true,
    });
}

// here comes the part of the code is executed without api error

Example on Server /api/example/load

export default defineEventHandler(async (event) => {
 
    const { id } = await readBody(event);

    if (!id) {
        return createError({
            statusCode: 401,
            statusMessage: "You don't have the rights to access this resource",
        });
    }

    return {
       data: '' // your stuff
    };
});

Upvotes: 0

Kendouci Ilyes
Kendouci Ilyes

Reputation: 51

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

Upvotes: 0

floriankapaun
floriankapaun

Reputation: 817

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

Upvotes: 2

Klas
Klas

Reputation: 186

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.

Upvotes: 2

Aborn Jiang
Aborn Jiang

Reputation: 1059

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

Upvotes: 10

Related Questions