nuxt / nuxt

The Intuitive Vue Framework.
https://nuxt.com
MIT License
52.99k stars 4.86k forks source link

Catch $fetch errors globally #27493

Open yooneskh opened 3 weeks ago

yooneskh commented 3 weeks ago

Environment


Reproduction

<script setup>

async function testOne() {
  await $fetch('https://non.existing/link');
  // code that should not execute
}

async function testTwo() {
  await $fetch('https://existing.api/but/gives/error');
  // code that should not execute
}

</script>

<template>
  <button @click="testOne(); testTwo();">
    Run
  </button>
</template>

Describe the bug

How is it possible to catch $fetch errors globally? As you can see in my repro, i have api calls which I want to proceed only if the call has succeeded, and I want the $fetch errors from everywhere to be handled in one place. I thought this would work

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.config.errorHandler = (error, instance, info) => {
    console.log(error);
  }
  nuxtApp.hook('vue:error', (error, instance, info) => {
    console.log(error);
  })
})

But it does not (for $fetch, it works for other things). NuxtErrorBoundary does not work too.

<template>
  <nuxt-error-boundary @error="console.log">
    ...
  </nuxt-error-boundary>
</template>

And if I give an onResponseError to the $fetch, although it gives me the error, but it does not halt execution, like throwing.

Is there any workaround?

Additional context

No response

Logs

No response

MuhammadM1998 commented 3 weeks ago

You can create a customized fetch instance and do the global error handling in the onResponseError hook. Then you use that custom fetch in your app https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-fetch

yooneskh commented 3 weeks ago

@MuhammadM1998 thank you for replying. The issue with onResponseError is that it does not halt the execution of the code (like throwing does). Also, without the global catching of the errors, the errors will be shown in the console which I like to avoid.