简体   繁体   English

如何从 Axios 中的 HTTP 错误获取状态码?

[英]How can I get the status code from an HTTP error in Axios?

This may seem stupid, but I'm trying to get the error data when a request fails in Axios.这可能看起来很愚蠢,但我试图在 Axios 中请求失败时获取错误数据。

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

Instead of the string, is it possible to get an object with perhaps the status code and content?除了字符串,是否有可能获得一个带有状态代码和内容的 object? For example:例如:

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

What you see is the string returned by the toString method of the error object.你看到的是error对象的toString方法返回的字符串。 ( error is not a string.) error不是字符串。)

If a response has been received from the server, the error object will contain the response property:如果从服务器接收到响应,则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);
    }
  });

With TypeScript, it is easy to find what you want with the right type.使用 TypeScript,很容易找到你想要的正确类型。

This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.这使一切变得更容易,因为您可以通过自动完成获得该类型的所有属性,因此您可以了解响应和错误的正确结构。

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

Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:此外,您可以将参数传递给两种类型,以告知您在response.data中的期望,如下所示:

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

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log , which varies and (imo) makes checking errors incredibly annoying.正如@Nick 所说,您在console.log一个 JavaScript Error对象时看到的结果取决于console.log的确切实现,这会有所不同并且(imo)使检查错误非常烦人。

If you'd like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify :如果您想查看完整的Error对象以及绕过toString()方法携带的所有信息,您可以使用JSON.stringify

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

There is a new option called validateStatus in request config.请求配置中有一个名为validateStatus的新选项。 You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior).您可以使用它来指定当状态 < 100 或状态 > 300(默认行为)时不引发异常。 Example:例子:

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

You can use the spread operator ( ... ) to force it into a new object like this:您可以使用扩展运算符 ( ... ) 将其强制转换为这样的新对象:

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

Be aware: this will not be an instance of Error.请注意:这不会是 Error 的实例。

I am using this interceptors to get the error response.我正在使用这个拦截器来获取错误响应。

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

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

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:为了获取服务器返回的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);
});

This way, every http response resolves the promise returned from axios.这样,每个 http 响应都会解析从 axios 返回的承诺。

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

Whole error can only be shown using error.response like that :整个错误只能使用 error.response 来显示:

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });
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
  });

}; };

See the console log then you will understand clearly看控制台日志你就明白了

在此处输入图像描述

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

    })

You can put the error into an object and log the object, like this:您可以将错误放入一个对象并记录该对象,如下所示:

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

It's indeed pretty weird that fetching only error does not return an object.仅获取错误不返回对象确实很奇怪。 While returning error.response gives you access to most feedback stuff you need.在返回error.response 时,您可以访问所需的大多数反馈信息。

I ended up using this:我最终使用了这个:

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

Which gives strictly the stuff I need: status code (404) and the text-message of the error.这严格提供了我需要的东西:状态代码(404)和错误的文本消息。

This is a known bug, try to use "axios": "0.13.1"这是一个已知的错误,尝试使用"axios": "0.13.1"

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

I had the same problem so I ended up using "axios": "0.12.0" .我遇到了同样的问题,所以我最终使用了"axios": "0.12.0" It works fine for me.这对我来说可以。

Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

It's my code: Work for me这是我的代码:为我工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM