根据响应状态,我可以在axios post中抛出错误
是否有可能在axios中的.then()块内故意抛出错误?例如,如果api响应204状态码,我可以抛出一个错误并运行catch块吗?根据响应状态,我可以在axios post中抛出错误
例如:
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,仍执行然后block()代替catch块。
EDIT 2
使用伊拉里奥的建议正确的答案是这样的:
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 Project Page,您会注意到以下选项说明。
/* `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
},
所以,你可以创建自己的配置个案。
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
},
});
您也可以设置默认值。这些将应用于每个请求。
axios.defaults.validateStatus =() => {
return status == 200;
};
更新1
设置config只能在特定的操作,你可以用你的所需值或方法替代“配置”。
axios.post(url[, data[, config]])
更新2
我想这一点,但没有奏效。
您不能将实例传递给axios.post()。您必须在新实例上调用帖子。
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
}
});
instance.post('url', data, config);
非常感谢您的建议。答案比我预想的要简单。
我不想设置任何默认选项来更改axios的行为,所以我只是尝试类似下面的代码,它的工作。每次执行代码throw new Error("Error");
时,都会在此之后执行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)
});
不客气:)为什么你不想设置默认选项?或者用这些选项创建一个实例?你只需要一个特定的请求?更新了我的答案。 –
再次感谢您的反馈!我只需要一个特定的请求 – jenny
Okaay。所以如果你只需要一个特定的请求,你可以按照你的建议来做,或者看看我的答案中的“更新1”。 –
现在很高兴它现在工作! –