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

Ter*_*ård 2 vue.js axios vuejs2

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

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

事情的方式..

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

2)触发状态动作以设置突变类型和调用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 ????)
                }
            })
        }
Run Code Online (Sandbox Code Playgroud)

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;

        })
    },
Run Code Online (Sandbox Code Playgroud)

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

            })
    });
}
Run Code Online (Sandbox Code Playgroud)

tha*_*ksd 5

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

.catch(error => {
  console.log('=== ERROR ====');
  console.log( error.response );
  reject(error)
})
Run Code Online (Sandbox Code Playgroud)

然后,您应该在doRefundaction方法中抛出错误:

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

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

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