【问题标题】:Catch() not handling 404Catch() 不处理 404
【发布时间】:2017-04-17 22:32:28
【问题描述】:

我正在编写一个脚本来从我的 api 中获取一些数据:

const success = (response) => {
  console.log(response);
};

const failed = (error) => {
  console.log(error);
};

axios.$http.get('/somedata')
  .then((response) => {
    success(response.data);
  })
  .catch((error) => {
    failed(error);
  });

/somepage 是一个不存在的页面,因此它返回 404。但问题没有处理这个问题。为什么不?在我的控制台中出现错误TypeError: Cannot read property 'data' of undefined。为什么它不运行failed() 函数?我不明白。

【问题讨论】:

标签: javascript api exception-handling promise catch-block


【解决方案1】:

发现它与处理 401 错误(但不是 404 错误)的自定义拦截器有关...

【讨论】:

  • 大概你的意思是“......一个自定义拦截器,它旨在处理 401 错误并且应该重新抛出所有其他错误......但没有” ?
【解决方案2】:

从错误信息来看,它看起来像“success(response.data);”正在被调用。服务器是否有可能成功返回一个显示“错误 404”之类的页面,而不是实际返回 http 响应代码 404?

【讨论】:

    【解决方案3】:

    您可以对 404 进行检查。

    axios.$http.get('/somedata')
      .then(response => {
        if(response.status !== 404) //or any status code really
            success(response.data);
        else
            failed(response)
      })
      .catch((error) => {
        failed(error);
      });
    

    那么您可能想要再次检查的是确保返回的是 200。

    axios.$http.get('/somedata')
      .then(response => {
        if(response.status === 200)
            success(response.data);
        else
            failed(response)
      })
      .catch((error) => {
        failed(error);
      });
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 2011-04-01
      • 2022-01-05
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2013-01-21
      相关资源
      最近更新 更多