DEV Community

Shimju David
Shimju David

Posted on

1

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 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);
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay