使用Vuex和Axios进行Vuejs错误处理的最佳实践

Lor*_*rim 11 vue.js axios vuex

我正在使用Vuex + axios,我想知道处理vuex + axios错误的最佳实践.我现在正在做的是,当我请求使用axios并且它返回错误时,它将在变异中提交并更新我的状态.我想要做的是,如果我的请求有响应错误,它将返回到我的组件,以便我可以更快地处理错误.

就像在角度中一样,有一个依赖注入,响应将返回到组件.

Phi*_*hil 16

吃蛋糕也吃.假设你已经在使用拦截器 ......

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  store.commit('ERROR', error) // just taking some guesses here
  return Promise.reject(error) // this is the important part
})
Run Code Online (Sandbox Code Playgroud)

这将使承诺拒绝回到调用者,所以在您的组件中,类似于......

axios.whatever(...).then(res => {
  // happy days
}, err => {
  // oh noes!
})
Run Code Online (Sandbox Code Playgroud)


Him*_*rma 6

让我告诉你我用于错误记录的方法是这个。 这样,您可以通过on代码处理所有vue错误。

window.onerror = function (message, source, lineno, colno, error) {
  /// what you want to do with error here
};
Run Code Online (Sandbox Code Playgroud)

这是浏览器的全局错误处理程序。如果未发现任何错误,可以通过此方法处理。

另外,如果您想处理您的错误。你可以这样

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
      // when you throw error this will also fetch error.
       throw error;
  });
Run Code Online (Sandbox Code Playgroud)

如果您想在vue上进行错误处理,可以使用。 https://vuejs.org/v2/api/#errorHandler

Vue.config.errorHandler = function (err, vm, info) {
  // handle error
  // `info` is a Vue-specific error info, e.g. which lifecycle hook
  // the error was found in. Only available in 2.2.0+
}
Run Code Online (Sandbox Code Playgroud)

让我给您一个链接,其中使用window.onerror

https://github.com/stacktracejs/stacktrace.js/

  • 先生,我也会研究的,谢谢您的回答。 (2认同)

fre*_*red 5

我只是使用捕获。我在切换到 vuex 之前使用的相同的东西。它可能是最通用且文档齐全的解决方案,让我可以像以前一样继续将错误插入到组件的 html 中。它还让我继续使用我的 loading = true, loading = false html 动画。

所以我最终得到 3 个状态属性,数据,错误和加载。它似乎对我有用。你的旅费可能会改变。我也在使用 vuex 模块和命名空间,但这里是一个没有它的简化示例

//somevuexstore.js

actions: {

fetchData(context) {

    axios
        .get("api/someendpoint")
        .then(response => {
            context.commit('loading')
            context.commit('organizations', response.data)

        }).catch(error => {
            console.log(error.response.data.message || error.message)
            context.commit('error', error)
        });
},

mutations: {
organizations(state, data) {
    return state.organization = data
},

error(state, data) {
    return state.error = data
},

loading(state) {
    return state.loading = false
},

state= {

organization: [],
error: '',
loading: true
}
Run Code Online (Sandbox Code Playgroud)

然后在我的 component.vue 中,它与我之前的做法非常相似,只是添加了计算属性。

computed: {
...mapState({
        getError: 'error',
        getLoading: 'loading',
        getAllOrg: 'organization',
}),
}

mounted() {
      this.$store.dispatch('fetchData')
}
Run Code Online (Sandbox Code Playgroud)

我的 html 就是这样的东西。

<tr v-for="value in getAllOrg" :key="value.id">
   <td>{{ value.id }}</td>
   <td>{{ value.email }}</td>
   <td>{{ value.name }}</td>
   <td>{{ value.['created-at'] | formatDate }}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

我在适当的地方插入错误消息

<div v-if="getError" class="error">
   <p>{{ getError }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)

对于加载动画,我使用vue spinners包插入到适当的 html 中。

<div v-if="getLoading" style="height:37px;">
    <p>
      <bar-loader class="custom-class" color="#c2c2c2" 
      getLoading="getLoading" 
      :width="130"></bar-loader>
   </p>
Run Code Online (Sandbox Code Playgroud)