如何从 Vuex 操作中的 axios 函数返回错误消息以调度 catch(error)?

Uts*_*tha 6 vue.js vuejs2

我有一个操作,其中使用 axios 进行 ajax 调用,每当 axios 返回错误时,它都会被 axios catch 函数捕获,所以我想知道是否有可能抛出相同的错误来调度 catch 函数。

我试图 //throw new Error("test error inside"); 从 axios catch(error) 内部,但 dispatch 似乎没有捕捉到错误

vuex 商店上的操作代码

actions:{
    assignOrder(context, assign){
        axios.post('/assignOrder',assign)
                  .then((response) => {
                    console.log(response)
                  })
                  .catch((error) => {
                     //I want to throw error catched from here
                        console.log(error.response.data.errors)
                      //throw new Error("test error inside");
                    // }       
                  })
    }
}
Run Code Online (Sandbox Code Playgroud)

关于我的 vue 组件方法

methods:{
      setAssign(){
        this.assign.order_id = this.order.id
        if(this.validate()){
          this.errors = {};
          this.$store.dispatch('assignOrder', this.assign).then(() => {
            showNotify('success','Order has been assigned')
            this.$store.dispatch('getOrders',this.active)
          })
          .catch((error) => {
             //catch the error here
              alert(error)    
            })
        }
        else{
          this.showErr = true;
        }
      },
}
Run Code Online (Sandbox Code Playgroud)

我希望 axios 抛出捕获错误,该错误将通过调度捕获

Abd*_*ani 15

只需从您的操作中返回一个承诺,然后在您的组件上处理它:

actions: {
  assignOrder(context, assign) {
    return new Promise((resolve, reject) => {
      axios.post('/assignOrder', assign)
        .then((response) => {
          resolve(response)
        })
        .catch((error) => {
          reject(error.response.data.errors)
        })
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

并在您的组件上:

methods: {
  setAssign() {
    this.assign.order_id = this.order.id
    if (this.validate()) {
      this.errors = {};
      this.$store.dispatch('assignOrder', this.assign).then((res) => {
          showNotify('success', 'Order has been assigned')
          console.log(res)
          this.$store.dispatch('getOrders', this.active)
        })
        .catch((error) => {
          // catch the error 
          alert(error)
        })
    } else {
      this.showErr = true;
    }
  },
}
Run Code Online (Sandbox Code Playgroud)

承诺将返回 aresolve或 areject将绑定到您的thencatch