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

时间:2017-10-02 20:17:20

标签: vue.js vuejs2 axios

这很好,可能被标记为重复,如果是对不起。谷歌搜索很多找到如何实际做到这一点,没有任何适当的解决方案(虽然我不是一个vue专家..)

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

事物的方式......

1)从vue组件触发的方法。发货到$ store(modal.vue)

2)触发状态操作以设置mutationtype并调用API。

3)调用Api方法。

4)返回成功或错误,和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 );

            })
    });
}

1 个答案:

答案 0 :(得分:5)

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

.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;
})

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

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