我可以根据响应状态在axios post中抛出错误

jen*_*nny 7 javascript axios

是否有可能在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
    });
Run Code Online (Sandbox Code Playgroud)

编辑

我试过这个,但它不起作用:

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
            });
        });
Run Code Online (Sandbox Code Playgroud)

当我得到状态代码204时,仍然执行的块然后是()块而不是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
            });
        });
Run Code Online (Sandbox Code Playgroud)

现在,当状态代码不等于200时,执行catch块代码.

Ila*_*ler 11

如果您查看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
},
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用自己的配置创建实例.

var instance = axios.create({

   validateStatus: function (status) {

        return status == 200;
    },
});
Run Code Online (Sandbox Code Playgroud)

您也可以设置默认值.这些将应用于每个请求.

axios.defaults.validateStatus = () => {

    return status == 200;
};
Run Code Online (Sandbox Code Playgroud)

更新1

要仅在特定操作上设置配置,您可以使用所需的值或方法替换"config".

axios.post(url[, data[, config]])
Run Code Online (Sandbox Code Playgroud)

更新2

我尝试了这个,但它没有用.

您无法将实例传递给axios.post().您必须在新实例上调用post.

var instance = axios.create({

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

instance.post('url', data, config);
Run Code Online (Sandbox Code Playgroud)


jen*_*nny 5

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

我不想设置任何默认选项来更改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)
    });
Run Code Online (Sandbox Code Playgroud)

  • `if (response.status &gt;= 200 &amp;&amp; response.status &lt; 300) {` 更安全 (3认同)