当前位置:首页 > 操作系统 > Ios

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

例如

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

最后,apiRes将返回null.

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

当axios抛出错误时,最终如何使用错误响应.

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

解决方法:

根据the documentation,完整的响应可用作错误的响应属性.

所以我会在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

但是,如果最终要使用它,只需将其保存到一个变量中,即可在其中使用:

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

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!