使用axios post请求捕获错误信息体

114

我从后端代码发送状态码422,并在响应主体中包含错误描述。我使用以下axios post请求发布请求:

post: function(url, reqBody) {
    const request = axios({
        baseURL: config.apiUrl,
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': sessionStorage.getItem('token')
        },
        method: 'POST',
        data: reqBody,
        responseType: 'json'
    });
    return request
        .then((res) => {
            return res;
        })
        .catch((error) => {
            console.log(error);
            return error;
        })
}

问题在于当后端返回错误代码422时,我捕捉到的错误对象没有关于响应主体的信息。是否有任何方法可以获取错误文本?

7个回答

204

我曾经遇到过同样的问题,答案是(根据Axios版本0.13及以上),需要特别检查error.response.data

axios({
    ...
}).then((response) => {
    ....
}).catch((error) => {
    if( error.response ){
        console.log(error.response.data); // => the response payload 
    }
});

更多详情请参见此处


43

AXIOS的错误响应的“body”取决于请求的响应类型。

如果您想要关于此问题的完整详细信息,可以查看此博客文章:如何捕获AXIOS错误中的body

总之,AXIOS将根据错误返回3种不同的body:

  1. Wrong request, we have actually done something wrong in our request (missing argument, bad format), that is has not actually been sent. When this happen, we can access the information using error.message.

    axios.get('wrongSetup')
    .then((response) => {})
    .catch((error) => {
        console.log(error.message);
    })
    
  2. Bad Network request: This happen when the server we are trying to reach does not respond at all. This can either be due to the server being down, or the URL being wrong. In this case, we can access the information of the request using error.request.

    axios.get('network error')
    .then((response) => {})
    .catch((error) => {
        console.log(error.request );
    });
    
  3. Error status: This is the most common of the request. This can happen with any request that returns with a status that is different than 200. It can be unauthorised, not found, internal error and more. When this error happen, we are able to grasp the information of the request by accessing the parameter specified in the snippets below. For the data (as asked above) we need to access the error.response.data.

    axios.get('errorStatus')
    .then((response) => {})
    .catch((error) => { 
         console.log(error.response.data);  
         console.log(error.response.status);  
         console.log(error.response.headers); 
     })
    

2
这可能发生在任何返回状态码不是200的请求上。我会说除了2XX/3XX以外的状态码。 - Andrii Abramov
1
不错的概述。但也许值得一提的是,服务器可能会有响应,但error.response仍然可能是未定义的。如果我们的服务器发送504(包括一些HTML数据),这种情况就会发生在我身上。我猜这是因为浏览器由于CORS而被阻止了? - kca

28

对于那些使用await/async和Typescript的人

try {
    const response = await axios.post(url, body)
} catch (error) {
    console.log(error.response.data);
}

9

对于React Native,它对我而言很好用。

api.METHOD('endPonit', body)
  .then(response => {
   //...
  })
  .catch (error => {
    const errorMessage = JSON.parse(error.request.response)
    console.log(errorMessage.message)
  })

2
我们可以像@JoeTidee所说的那样检查error.response.data。但在响应负载是blob类型的情况下,您可以使用以下代码获取错误响应体。
axios({
    ...
}).then((response) => {
    ....
}).catch(async (error) => {
    const response = error.response
    if(typeof response.data.text === function){
        console.log(await response.data.text()); // => the response payload 
    } else {
        console.log(response.data)
    }
});

2
在我的情况下,我想要检索一个响应404错误消息(正文)。 我使用error.response.data获取了正文,但是由于类型为ArrayBuffer,所以无法显示它。
解决方案:
axios.get(url, { responseType: 'arraybuffer' }).then(
   response => {...},
   error => {
      const decoder = new TextDecoder()
      console.log(decoder.decode(error.response.data))
   }
)

相关文章: 在字符串和ArrayBuffers之间进行转换


0
我从后端返回了一个字符串,但期望响应类型为 JSON。因此,我需要返回一个对象而不是字符串,以便让 axios 正确处理它。

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