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

559

这可能看起来很蠢,但我正在尝试在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'}
16个回答

3

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

    })

2

仅获取error时返回的确实很奇怪,它并不会返回一个对象。而返回error.response则可以让你访问大部分所需的反馈信息。

我最终使用了以下代码:

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

这将严格提供我所需的内容:状态码(404)和错误的文本消息。


1

1
这不是我遇到的同样问题,甚至在我记录“error”时没有涉及任何对象。 - Sebastian Olsen

1
你可以将错误放入对象中并记录该对象,例如:

您可以这样:

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

1

Axios错误包含了很多信息,但是如果你只是用普通的console.log(error)打印出来,你只会得到一个类似于“Error: Request failed with status code XXX”的通用错误信息。

这里提供一种使用TypeScript处理Axios错误和其他错误的解决方案。

axios.get('foo.example')
    .then((response) => {//...})
    .catch (error: any) {
        let errorResponse: any;

        // it is an AxiosError
        if (error?.isAxiosError) {
            const axiosError = error as AxiosError;
            errorResponse = axiosError.response; //all the info here
        } else {
            errorResponse = error; // it is not an AxiosError
        }

        console.log(errorResponse);
        throw errorResponse;
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接