这可能看起来很愚蠢,但我试图在Axios中获得请求失败时的错误数据。

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

而不是字符串,是否有可能获得一个对象的状态代码和内容?例如:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

当前回答

只抓取错误却不返回对象,这确实很奇怪。返回错误。回应能让你获得你需要的大部分反馈。

最后我用了这个:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

它严格地提供了我需要的东西:状态码(404)和错误的文本消息。

其他回答

你可以使用扩展操作符(…)强制它进入一个新的对象,就像这样:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({...error})
})

注意:这将不是Error的实例。

整个错误只能用error来显示。这样的回答:

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

这是一个已知的错误,尝试使用"axios": "0.13.1"

https://github.com/mzabriskie/axios/issues/378

我遇到了同样的问题,所以我最终使用了“axios”:“0.12.0”。这对我来说很有效。

在请求配置中有一个名为validateStatus的新选项。您可以使用它来指定如果状态< 100或状态> 300(默认行为)不抛出异常。例子:

const {status} = axios.get('foo.example', {validateStatus: () => true})

你可以把错误放入一个对象并记录该对象的日志,如下所示:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });