这可能看起来很愚蠢,但我试图在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": "0.13.1"

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

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

您看到的是错误对象的toString方法返回的字符串。(错误不是一个字符串。)

如果从服务器接收到响应,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);
    }
  });

我使用这个拦截器来获得错误响应。

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

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

正如@Nick所说,当你在console.log中设置一个JavaScript错误对象时,你所看到的结果取决于console.log的确切实现,这使得检查错误变得非常烦人。

如果你想看到完整的Error对象和它所携带的所有信息,绕过toString()方法,你可以使用JSON.stringify:

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

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

这使一切都变得更简单,因为您可以使用自动完成获得类型的所有属性,因此您可以知道响应和错误的正确结构。

import { AxiosResponse, AxiosError } from 'axios'

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

此外,您还可以向这两种类型传递一个参数,以告知您所期望的内部响应。数据如下:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
  .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)
  })

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

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

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

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

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

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

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

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

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

这是我的准则:为我工作

 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")
    })
Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

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

最后我用了这个:

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

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

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

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

与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)
        }

    })
const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

看看控制台日志,你就明白了