catching error body using axios post
Full error message
I am sending a status code 422 from my backend code with response body which contains the description of the error. I am using axios post as below to post a request:
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;
})
}
The problem is when backend is returning error code 422, the error object I am catching has no information about response body. Is there any way I can retrieve the error text?Solutionsource: stackoverflow \u2197
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.
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/0596aff013f814ad90bc110dab4c0a9e67c6614bc90abe8daf232fb88c46c959hash \u00b7 0596aff013f814ad90bc110dab4c0a9e67c6614bc90abe8daf232fb88c46c959