繁体   English   中英

如何在 Axios 中捕获错误 404 错误?

[英]How to get catch error 404 error in Axios?

我有这段代码(函数的一部分),注意 URL 末尾的“ BadURL ”:

从“axios”导入 axios;

try {
  return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  });
} catch (error) {
  return { data: 'false' }
}

但是不能进入catch块,说:

(node:7676) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404

仅当我将函数调用本身包装在类之外时,我才能捕获错误

Axios.post(...)是一个异步调用,它返回一个 promise,该语句不会失败,即使失败,也不是因为 HTTP 请求失败。

你需要使用什么.then().catch()返回的承诺来处理请求的方法。

return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false"
}).then((results) => {
    console.log('yay', results);
}).catch((error) => {
    console.log('oops', error);
});

另一种选择是使用async await

async function handler() {
    try {
        const results = await axios.post("http://localhost:5000/api/featureFlagBadURL", {
            flagName: "newJqueryAjaxListener",
            defaultValue: "false",
        });
        console.log('yay', results);
    }
    catch (error) {
        console.log('oops', error);
        return { data: 'false' };
    }
})

试试这个方法:

  return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  }).then(function (response) {
    // handle success
    console.log(response);
  }).catch(function (error) {
    // handle error
    console.log(error);
  }).then(function () {
    // always executed
  });

来源

您可以捕获错误并检查状态代码。 那么你可以处理它。 也许巫婆开关案例或简单的如果。 我是为 404 做的。 见下面的鳕鱼:

axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  }).then((res) => {
    // handle response => res.data
    console.log(response);
  }).catch((error) => {
    if (error.response) {
      if(error.response.status === 404) {
        console.log('BAD URL')
        // or 
        console.log(error.response.statusText) // "Not Found" 
      }
    }
  }

如果函数有大量数据,请尝试通过将代码包含在函数中来使用异步等待。

或者尝试将端口从 5000 更改为 4000 或 3000。看看这是否有效!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM