公理。即使在 api return 404 错误时如何获得错误响应,最后在 try catch 中

Axios. How to get error response even when api return 404 error, in try catch finally

例如

(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);
  }
})();

finally 中,apiRes 将 return 为空。

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

axios抛出错误时如何使用finally中的错误响应

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

根据 the documentation,完整的响应可以作为错误的 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);
  }
})();

Updated Fiddle

但是如果你想在 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
  }
})();

根据 AXIOS 文档(此处:https://github.com/axios/axios),您可以将配置对象中的 validateStatus: false 传递给任何 axios 请求。

例如

axios.get(url, { validateStatus: false })
axios.post(url, postBody, { validateStatus: false })

你也可以像这样传递一个函数:validateStatus: (status) => status === 200 根据文档,默认行为是函数 returns true if (200 <= status < 300).

您可以对待状态码:

使用 Ts 的示例:

let conf: AxiosRequestConfig = {};

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

    let response = await req.get(url, conf);