DEV Community

Shimju David
Shimju David

Posted on

How to properly catch Express-Validator errors returned by Axios

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'', formData);

    // Success 🎉
} 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
    } 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
    } else {
        // Something happened in setting up the request and triggered an Error
        console.log('Error', error.message);

Top comments (0)