[英]Can I throw error in axios post based on response status
是否可以在 axios 的 .then() 块内故意抛出错误? 例如,如果 api 响应 204 状态代码,我可以抛出错误并运行 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 } }).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 },
因此,您可以使用自己的配置创建一个实例。
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()。 您必须在新实例上调用 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) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.