【问题标题】:Catching errors with axios使用 axios 捕获错误
【发布时间】:2018-03-25 01:05:01
【问题描述】:

我无法使用 axios 捕获错误响应。怎么做? 我使用类似的东西:

axios
  .post(...)
  .then(response => {
    console.log('Success: ', response)
  }).catch(error => {
    console.log('Error: ', error)
  })

我看到 ajax 请求的结果有 400 个状态码,响应体看起来像 {someField:["This field may not be blank"]}(Django 后端)。没关系,我已经准备好在 catch 处理程序中处理这些错误了。

但他们改为转到成功处理程序。为什么这样?我在控制台中看到以下输出:

Success: Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)

成功处理程序接收 axios 错误对象作为结果。为什么会这样,下一步该怎么做?此错误对象不包含任何有用的信息。

UPD。实际上,错误对象确实包含有用的信息,它包含在里面的响应对象。所以我们可以使用:

axios
  .post(...)
  .then(response => {
    if (response && response.response) {
      console.log('This is also an error', response.response.status)
    } else {
      console.log('Success: ', response)
    }
  }).catch(error => {
    console.log('Error: ', error)
  })

但这看起来超级难看。

axios版本是axios@0.16.2。

这是一个大项目,但我找不到任何 axios 自定义。

【问题讨论】:

  • 我认为您正在寻找拦截器...(我正在寻找相同的,以处理 503 错误,但仍然没有弄清楚如何使其在我的代码中工作)

标签: ajax axios


【解决方案1】:

使用 Axios 拦截器进行响应。检查您想强制哪个状态作为错误失败,以便在您收到所述状态代码时通过catch 路径。

axios.interceptors.response.use(function (response) {
    if (response.status === 400) {
        return Promise.reject(response);
    }
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});

如果您没有收到预期的状态代码,您可能会更改在拦截器中检查响应的方式。您可以检查Axios response is structured 的任何元素。

axios.interceptors.response.use(function (response) {
    if (response.statusText !== 'OK') {
        return Promise.reject(response);
    }
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});

【讨论】:

  • 谢谢。实际上,所描述行为的原因是应用程序的另一部分中已经存在不正确的拦截器。默认情况下 axios 做的事情是正确的——它处理服务器响应代码并触发错误处理程序,以防它不是 2xx。想象一下,你的拦截器没有在 catch 错误处理程序中执行 Promise.reject。这正是我所拥有的 - 所有响应代码都转到了成功处理程序。
猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 2021-07-05
  • 2018-04-19
  • 2021-07-27
  • 2018-09-25
  • 2019-06-26
  • 2021-04-02
相关资源
最近更新 更多