How to handle HTTP 400 Error in Axios

May 29, 2020

Axios is a light weight promised based HTTP client for both nodejs and browser.

Let’s see how to handle 400 error message using it.

What is HTTP 400 status code?

HTTP status code 400 is sent by the server in response to our api call if we have a client side error like the data that we sent is invalid in someway like validation issue

Handling 400 error message in Axios

Depedency

npm i axios

Snippet

const axios = require("axios");

const doSomething = async () => {
  try {
    await axios.post("https://httpbin.org/status/400", {});
  } catch (error) {
    console.log(error.response);

    // Check if it's HTTP 400  error
    if (error.response.status === 400) {
      console.log(`HTTP 400 error occured`);
    }
    // You can get response data (mostly the reason would be in it)
    if (error.response.data) {
      console.log(error.response.data);
    }
    // TODO: throw error if you want to handle it somewhere
    // throw error;
  }
};

doSomething();

Playground

Here’s a Codesandbox snippet for you to play around


👋 I'm Ashik Nesin • Principal Software Engineer @Chargebee 👨‍💻• I write about web development & behinds the scenes of startup/side projects that I'm building

© 2022 Nesin Technologies LLP