是否有可能在 axios 中的 .then() block 内故意抛出错误?例如,如果 api 以 204 状态代码响应,我可以抛出错误并运行 catch block 吗?
例如:
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 仍然是 then() block 而不是 catch block 。
编辑 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 block 代码。
最佳答案
如果您查看 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
I tried this, but it didn't work.
您不能将实例传递给 axios.post()。您必须在新实例上调用 post。
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
}
});
instance.post('url', data, config);
关于javascript - 我可以根据响应状态在 axios post 中抛出错误吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43842711/