Axios。即使在api返回404错误时也如何获得错误响应,请尝试尝试最终捕获

Jac*_*Goh 9 javascript error-handling axios

例如

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error(err);
  } finally {
    console.log(apiRes);
  }
})();
Run Code Online (Sandbox Code Playgroud)

中的finallyapiRes将返回null。

即使api收到404响应,响应中仍然有一些我想使用的有用信息。

finally当axios引发错误时,如何使用错误响应。

https://jsfiddle.net/jacobgoh101/fdvnsg6u/1/

T.J*_*der 18

根据文档,完整的响应可用作response错误的属性。

因此,我将在catch块中使用该信息:

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    console.error("Error response:");
    console.error(err.response.data);    // ***
    console.error(err.response.status);  // ***
    console.error(err.response.headers); // ***
  } finally {
    console.log(apiRes);
  }
})();
Run Code Online (Sandbox Code Playgroud)

更新的小提琴

但是,如果您希望将其finally保存在其中,只需将其保存到变量中即可在此处使用:

(async() => {
  let apiRes = null;
  try {
    apiRes = await axios.get('https://silex.edgeprop.my/api/v1/a');
  } catch (err) {
    apiRes = err.response;
  } finally {
    console.log(apiRes); // Could be success or error
  }
})();
Run Code Online (Sandbox Code Playgroud)

  • 您还可以在[此处](https://github.com/axios/axios/blob/master/index.d.ts#L85)查看“err”类型定义以查找其他有用的数据:) (3认同)

Oli*_*ver 6

根据AXIOS文档(这里:https : //github.com/axios/axios),您可以将validateStatus: falseconfig对象传递给任何axios请求。

例如

axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })
Run Code Online (Sandbox Code Playgroud)

您还可以传递如下函数:validateStatus: (status) => status === 200 根据文档,默认行为是如果(200 <= status <300)返回true的函数。


小智 5

您可以处理状态码:

使用 T 的示例:

let conf: AxiosRequestConfig = {};

    conf.validateStatus = (status: number) => {
        
        return (status >= 200 && status < 300) || status == 404
    }

    let response = await req.get(url, conf);
Run Code Online (Sandbox Code Playgroud)