[英]Axios 400 error request call then instead of catch
I have this function:我有这个 function:
add(App, Params, Callback){
var self = this;
var Data = self.process_fields(Params)
self.$http.post(
paths.api + '/app/' + App.Permalink,
new URLSearchParams(Data)
).then(function (error, response) {
console.log("then");
if (typeof (Callback) == "function") {
Callback(true, response.data.data);
}
}).catch(function(error){
console.log("catch");
if(typeof error.response !== "undefined"){
errors.render(error.response.data.error)
}
if (typeof (Callback) == "function") {
Callback(false, null);
}
});
}
When i call request and recieve a 400 error, it calls then instead of catch:当我调用请求并收到 400 错误时,它调用 then 而不是 catch:
I found the solution 我找到了解决方案
Problem caused by dont return promise in axios interceptors: 在axios拦截器中不返回承诺引起的问题:
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (!error.response) {
alert('NETWORK ERROR')
} else {
const code = error.response.status
const response = error.response.data
const originalRequest = error.config;
if (code === 401 && !originalRequest._retry) {
originalRequest._retry = true
auth.commit('logout');
window.location.href = "/login";
}
return Promise.reject(error)
}
});
adding return Promise.reject(error)
works like a charm 添加return Promise.reject(error)
就像一个魅力
This is on purpose in older version of Axios.这是 Axios 的旧版本中的目的。
validateStatus
has been added into config since v0.11.从 v0.11 开始, validateStatus
已添加到配置中。 We can use this option to specify valid status code range.我们可以使用此选项来指定有效的状态代码范围。 By default, valid code is >= 200 and < 300.默认情况下,有效代码为 >= 200 且 < 300。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
Ref:https://github.com/axios/axios/issues/41#issuecomment-215100137参考:https://github.com/axios/axios/issues/41#issuecomment-215100137
Add a response interceptor like添加一个响应拦截器,如
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.