我正在使用Axios从Vuex商店中发布到api,当api从服务器返回错误时,它会抛出一个错误,该错误无法在try catch块中捕获 .

// 那个行动

async register({ commit }, params) {
    // I use an axios interceptor to format all responses like this 
    // so I can avoid having to use try-catch at least when using axios.
    const [res, { error }] = await Vue.axios.post(`${params.type}`, params);
    if (error) {
      throw new Error(error);
    }

//在组件中

try {
  const response = await this.$store.dispatch('handleAuthEvent', payload);
  // do stuff with response
} catch (error) {
  // `error` here is not defined, even though I passed it in the `throw` from the backend
  this.showError();
}

// main.js

import axios from './axiosConfig.js'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

// axiosConfig.js

import axios from 'axios'

const API_URL = process.env.API_URL || 'http://localhost:3030/'

const instance = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.token
  }
})

// format response data to avoid having to use try/catch blocks with async/await
instance.interceptors.response.use(data => {
  return [data, null];
}, error => {
  return [null, error.response.data.error || "server error"];
});

export default instance;