使用 axios 捕获错误

Catching errors with axios

我无法用 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 错误对象作为结果。为什么会这样,下一步该怎么做?此错误对象不包含任何有用信息。

更新。实际上,error 对象确实包含了有用的信息,它里面包含了 response 对象。所以我们可以使用:

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 定制。

使用 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);
});