使用轴线柱捕捉错误体

我发送了一个状态代码422从我的后端代码与响应体,其中包含了错误的描述。我使用 Axios 帖子如下发布请求:

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时,我捕获的错误对象没有关于响应体的信息。有什么办法可以检索错误文本吗?

95713 次浏览

I am returning a string from backend but expecting a json as response type. So I need to return an object instead of string for axios to process it properly.

I had this same issue and the answer (as per Axios >= 0.13) is to specifically check error.response.data:

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

See here for more details.

The "body" of an AXIOS error response depends from the type of response the request had.

If you would like full details about this issue you can see this blogpost: How to catch the body of an error in AXIOS.

In summary AXIOS will return 3 different body depending from the error:

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

For those using await/async and Typescript

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

For react native it just worked for me

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

We can check error.response.data as @JoeTidee said. But in cases response payload is blob type? You can get error response body with the below code.

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

In my case I wanted to retrieve a response 404 error message (body). I got body with error.response.data but I couldn't display it because the type was ArrayBuffer.

Solution:

axios.get(url, { responseType: 'arraybuffer' }).then(
response => {...},
error => {
const decoder = new TextDecoder()
console.log(decoder.decode(error.response.data))
}
)

Related posts: Converting between strings and ArrayBuffers