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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Retry later