VUE 和 Axios API:将错误代码从 api 传递到存储到 vue 组件

VUE and Axios API : Passing error code from api, to store, to vue component

这很好,可能会被标记为重复,如果是,我很抱歉。一直在谷歌上搜索 很多 以找到如何实际执行此操作,但没有任何适当的解决方案(虽然我不是 vue 专家..)

基本上..我正在尝试做的..从 api => store => vue 组件传递成功或失败。如果出错...我将向用户显示错误代码(目前...)

事物的方式..

1) 从vue组件触发的方法。派送至 $store (modal.vue)

2) 触发状态动作设置突变类型并调用API.

3) Api 方法被调用。

4) 返回成功或错误,AND http.statuscode.....

MODAL.VUE

doRefund: function(){
            this.$store.dispatch('doRefund', {
                    Username : this.loggedInUser.account.username,
                    OrderID: this.selectedOrder.orderid,
                    IsFeeApplied: false,
                    CreditAmount: this.refundAmount,
                    ChargeFee: 0.0,
                    Reason: "reason-not-specified",
                    Description: this.comment,
                    BearerToken: "Bearer " + this.accessToken
            })
            .then(result => {
                if(result === true){
                  alertify.success('It worked!')
                }
                else{
                    alertify.alert('There was an error, and the errorcode is' + errorcode ????)
                }
            })
        }

STORE.JS

doRefund({ commit }, refundParams){
        api.tryRefund(refundParams)
        .then(refundCompleted => {
            commit(types.SET_REFUND_COMPLETED, true)
            return true;
        })
        .catch(err => {
            //TODO: How to i fetch, and pass the errorcode ? 
            commit(types.SET_REFUND_COMPLETED, false)
            return false;

        })
    },

API.JS

tryRefund(refundParams) {
    console.log('=== try ====');
    console.log( refundParams );
    return new Promise((resolve, reject) => {
        var config = {
            headers: {
                'Content-Type': ' application/json',
                'Authorization': refundParams.BearerToken
            }
        };
        return axios.post('the-url-to-the-service', refundParams, config)
            .then(
                () => resolve(true))
            .catch( error => {
                console.log('=== ERROR ====');
                console.log( error.response );

            })
    });
}

您需要将 error.response 传递给 api.js 文件中 tryRefund 方法中的 reject 处理程序:

.catch(error => {
  console.log('=== ERROR ====');
  console.log( error.response );
  reject(error)
})

那么,你应该在doRefund动作方法中抛出错误:

.catch(err => {
  //TODO: How to i fetch, and pass the errorcode ? 
  commit(types.SET_REFUND_COMPLETED, false)
  throw err;
})

然后在 $dispatch 方法的 catch 处理程序中捕获它:

this.$store.dispatch('doRefund', {
  ...               
})
.then(result => {
  ...
})
.catch(error => { 
  console.log(error); // this is the error you want
})