Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I use error function in Nuxt Plugin?

I'm using Nuxt and axios-module.

I trying to global error handling by axios global interceptor.

How Can I use error function in Nuxt Plugin?

// ~/plugins/axios.js

export default function ({ $axios, store, redirect, error }) {
 $axios
 .onError(apiError => {
   error({statusCode: '403', message: 'test'}) // It's not work.
   redirect('http://google.com') // It's work.
  })
}

redirect is working. but error not work. just display server error page.

like image 986
bombay Avatar asked Jul 01 '26 16:07

bombay


2 Answers

Now it's available in @nuxtjs/axios Helper 🎉

export default function ({ $axios, error: nuxtError }) {
  $axios.onError(error => {
    nuxtError({
      statusCode: error.response.status,
      message: error.message,
    });
    return Promise.resolve(false);
  })
}
like image 89
DengSihan Avatar answered Jul 03 '26 17:07

DengSihan


I have the same problem.

After checking my code.I found that when you request data only once in asyncData method, the error methods in plugin works. However, if you request several times, error method may not work. This method cannot stop returning data in asyncData method.

So, my solution is check the response both in the axios plugin you build and also check the response when you request several api with promise.all(). if not qualified, stop return data.

like image 27
MoonDuffy Avatar answered Jul 03 '26 15:07

MoonDuffy



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!