How Can I use error function in Nuxt Plugin?

狂风中的少年 提交于 2021-02-08 06:19:38

问题


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.


回答1:


Your plugin function should return a promise and resolved just after calling the error function because Nuxt.js treat plugin function like a promise. Just like this.

export default function ({ $axios, error }) {
  return new Promise(resolve => {
    $axios.onError(apiError => {
      error({ statusCode: 403, message: 'test' }))
      resolve()
    }
  })
}



回答2:


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.




回答3:


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



回答4:


You can use the Axios helper for Nuxt errors that help to handle interceptions.

export default function ({ $axios, store, redirect, error: nuxtError }) {
  $axios.onError(error => {
    nuxtError({
      statusCode: error.response.status,
      message: error.message,
      if(statusCode === 403){
        redirect('http://example.com')
      }
    });
    return Promise.resolve(false);
  })
}

See @nuxt/axios helpers for details and for more about that see extending axios



来源:https://stackoverflow.com/questions/51073213/how-can-i-use-error-function-in-nuxt-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!