簡體   English   中英

愛訊。 即使api返回404錯誤,如何在try catch finally中獲得錯誤響應

[英]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將返回 null。

即使 api 得到 404 響應,響應中仍然有我想使用的有用信息。

當 axios 拋出錯誤時,如何在finally中使用錯誤響應。

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

根據文檔 ,完整響應可用作錯誤的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);
  }
})();

更新小提琴

但是如果你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 ),您可以將config對象中的validateStatus: false傳遞給任何axios請求。

例如

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

您還可以傳遞這樣的函數: validateStatus: (status) => status === 200根據文檔,默認行為是函數,如果(200 <= status <300)則返回true。

您可以處理狀態碼:

使用 Ts 的示例:

let conf: AxiosRequestConfig = {};

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM