【问题标题】:Can I throw error in axios post based on response status我可以根据响应状态在 axios 帖子中抛出错误吗
【发布时间】:2017-05-08 08:08:59
【问题描述】:

是否可以在 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 块代码。

【问题讨论】:

  • 很高兴它现在可以工作了!!

标签: javascript axios


【解决方案1】:

如果您查看 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()。您必须在新实例上调用 post。

var instance = axios.create({

    validateStatus: function (status) {
        return status == 200;
    }
});

instance.post('url', data, config);

【讨论】:

    【解决方案2】:

    非常感谢您的建议。答案比我预想的要简单。

    我不想设置任何默认选项来改变 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)
        });
    

    【讨论】:

    • 不客气 :) 为什么你不想设置默认选项?或者创建一个设置了这些选项的实例?您是否仅在特定请求时才需要它?更新了我的答案。
    • 再次感谢您的反馈!我只需要它来处理一个特定的请求
    • 好的。因此,如果您仅针对特定请求需要它,您可以按照您的建议进行操作,或者查看我的回答中的“更新 1”。
    • if (response.status &gt;= 200 &amp;&amp; response.status &lt; 300) { 更安全
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2019-04-29
    • 2021-01-16
    • 2021-10-19
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多