Javascript 我可以根据响应状态在axios post中抛出错误吗
是否可能在axios中的.then()块内故意抛出错误?例如,如果api以204状态代码响应,我是否可以抛出一个错误并运行catch块 例如:Javascript 我可以根据响应状态在axios post中抛出错误吗,javascript,axios,Javascript,Axios,是否可能在axios中的.then()块内故意抛出错误?例如,如果api以204状态代码响应,我是否可以抛出一个错误并运行catch块 例如: axios.post('link-to-my-post-service', { json-input }).then(response => { if (response.status === 200) { //proceed... } else {
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
}
}).catch(error => {
//run this code always when status!==200
});
编辑
我试过这个,但没用:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
axios.post('link-to-my-post-service', {input: myInput}, instance)
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
当我得到一个状态代码204时,执行的块仍然是then()块,而不是catch块
编辑2
使用Ilario建议的正确答案是:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
instance.post('link-to-my-post-service', {input: myInput})
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
现在,当状态代码不等于200时,将执行catch块代码。如果查看GitHub,您将注意到以下选项描述
/* `validateStatus` defines whether to resolve or reject the promise for a given
* HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
* or `undefined`), the promise will be resolved; otherwise, the promise will be
*/ rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
您还可以设置默认值。这些将应用于每个请求
axios.defaults.validateStatus = () => {
return status == 200;
};
更新1
要仅在特定操作上设置配置,可以使用所需的值或方法替换“config”
axios.post(url[, data[, config]])
更新2
我试过了,但没用
无法将实例传递给axios.post()。您必须在新实例上调用post
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
}
});
instance.post('url', data, config);
非常感谢你的建议。答案比我想象的要简单 我不想设置任何默认选项来更改axios的行为,所以我只是尝试了下面的代码,效果很好。每次代码
抛出新错误(“错误”)执行代码>,然后执行catch块代码
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
throw new Error("Error");
}
}).catch(error => {
//when throw "Error" is executed it runs the catch block code
console.log(error)
});
不客气:)为什么不想设置默认选项?或者创建一个设置了这些选项的实例?你是否只需要一个特定的请求?更新了我的答案。再次感谢您的反馈!我只是为了一个特定的请求才需要它。因此,如果您只需要一个特定的请求,您可以按照您的建议来做,或者查看我的答案中的“更新1”。如果(response.status>=200&&response.status<300){
是安全的,它现在可以工作了!!
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
throw new Error("Error");
}
}).catch(error => {
//when throw "Error" is executed it runs the catch block code
console.log(error)
});