445

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

axios
  .get('foo.com')
  .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'}
4

14 回答 14

883

你看到的是对象的toString方法返回的字符串error。(error不是字符串。)

如果从服务器接收到响应,则该error对象将包含以下response属性:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });
于 2016-08-25T19:34:30.140 回答
42

使用 TypeScript,很容易找到你想要的正确类型。

这使一切变得更容易,因为您可以通过自动完成获得该类型的所有属性,因此您可以了解响应和错误的正确结构。

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.com')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

此外,您可以将参数传递给这两种类型,以告知您对内部的期望,response.data如下所示:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.com')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })
于 2019-09-17T03:03:12.217 回答
22

正如@Nick 所说,当您console.log使用 JavaScriptError对象时看到的结果取决于 的确切实现console.log,这会有所不同并且(imo)使检查错误非常烦人。

如果您想查看完整的Error对象以及绕过该toString()方法携带的所有信息,您可以使用JSON.stringify

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });
于 2017-02-14T09:17:33.807 回答
14

validateStatus请求配置中有一个新选项。您可以使用它来指定当状态 < 100 或状态 > 300(默认行为)时不引发异常。例子:

const {status} = axios.get('foo.com', {validateStatus: () => true})
于 2020-03-31T12:44:23.457 回答
11

您可以使用扩展运算符 ( ...) 将其强制转换为这样的新对象:

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

请注意:这不会是 Error 的实例。

于 2020-01-22T20:31:14.317 回答
9

我正在使用这个拦截器来获取错误响应。

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});
于 2016-12-05T16:41:08.560 回答
6

为了获取服务器返回的http状态码,可以validateStatus: status => true在axios选项中添加:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

这样,每个 http 响应都会解析从 axios 返回的承诺。

https://github.com/axios/axios#handling-errors

于 2020-05-07T11:48:23.553 回答
3

整个错误只能使用 error.response 来显示:

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });
于 2021-07-01T10:07:37.033 回答
1

您可以将错误放入一个对象并记录该对象,如下所示:

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

希望这可以帮助那里的人。

于 2020-01-22T21:29:29.973 回答
1

使用 Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })
于 2021-09-03T05:43:48.460 回答
1

仅获取错误不返回对象确实很奇怪。在返回error.response 时,您可以访问所需的大多数反馈信息。

我最终使用了这个:

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

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

于 2021-04-27T12:14:43.593 回答
0

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

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

我有同样的问题,所以我最终使用 "axios": "0.12.0". 这对我来说可以。

于 2016-08-25T19:24:07.100 回答
-1

这是我的代码:为我工作

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })
于 2020-07-04T12:17:57.307 回答
-2
Axios. get('foo.com')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})
于 2021-01-14T05:59:20.073 回答