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

当前回答

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

};

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

其他回答

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

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

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

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

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

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

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

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

这是我的准则:为我工作

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

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