How to properly catch Express-Validator errors returned by Axios
Shimju David
Posted on April 9, 2020
Many Express.js based API's extensively uses express-validator to validate their POST/ GET / PATCH requests and when we test it via postman, it normally returns proper error messages with status code. But when we call the endpoints via Axios in our client applications (Angular, React, Vue.js), it doesn't return the proper error messages as we expected.
To solve that issue we need to handle the error object returned by the Axios more precisely like below-
/*
* Handling Errors using async/await
* Has to be used inside an async function
*/
try {
const response = await axios.post('http://your.site/api/signup', formData);
// Success 🎉
console.log(response);
} catch (error) {
// Error 😨
if (error.response) {
/*
* The request was made and the server responded with a
* status code that falls out of the range of 2xx
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received, `error.request`
* is an instance of XMLHttpRequest in the browser and an instance
* of http.ClientRequest in Node.js
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error);
}
💖 💪 🙅 🚩
Shimju David
Posted on April 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.