这很好,可能会被标记为重复,如果是的话,我很抱歉。一直在谷歌搜索很多来找到如何实际做到这一点,但没有任何适当的解决方案(虽然我不是 vue 专家..)
基本上..我正在尝试做的事情..是从 api => store => vue 组件传递成功或失败。如果出现错误...我将向用户提供错误代码(目前...)
事情的方式..
1) 从 vue 组件触发的方法。调度到 $store (modal.vue)
2)触发状态 Action 来设置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 );
})
});
}
最佳答案
您需要通过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
})
关于vue.js - VUE和Axios API : Passing error code from api,来存储,到vue组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533084/