Axios 调用总是以 then() 回调结尾



我正在调用这个 Vuex 操作,该操作正在触发放在 try/catch 块中的 Axios 请求。

我称之为:

this.$store
  .dispatch('api/get', { url: url })
  .then(data => { console.log(data) })
  .catch(error => { console.log(error) })

Vuex 行动

async get({ commit }, payload) {
  try {
    let response = await this.$axios.get(payload.url, payload.data)
    return response.data
  } catch (e) {
    commit('notifications/PUSH_ALERT', {
      alert: e.response.data.message,
    })
  }
},

我的 API 返回错误,该错误在 catch {} 块的 Vuex 操作中被截获。

为什么仍然调用.then(response)回调?当然,响应是空的。

我以为.catch(error)会被召唤?

你可以

像这样再次throw它:

async get({ commit }, payload) {
  try {
    let response = await this.$axios.get(payload.url, payload.data)
    return response.data
  } catch (e) {
    commit('notifications/PUSH_ALERT', {
      alert: e.response.data.message,
    })
    // Throw error again when it is handled, so outer catch can handle it too
    throw e
  }
}

最新更新