Categories
JavaScript Answers

How to catch and handle error response 422 with Axios and JavaScript?

Spread the love

Sometimes, we want to catch and handle error response 422 with Axios and JavaScript.

In this article, we’ll look at how to catch and handle error response 422 with Axios and JavaScript.

How to catch and handle error response 422 with Axios and JavaScript?

To catch and handle error response 422 with Axios and JavaScript, we call catch with a callback to catch errors.

For instance, we write

axios
  .put(url, payload)
  .then((response) => {
    // ...
  })
  .catch((error) => {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      console.log(error.request);
    } else {
      console.log("Error", error.message);
    }
    console.log(error.config);
  });

to call catch with a callback that has the error parameter.

We get the error response code from the error.response.status property.

Conclusion

To catch and handle error response 422 with Axios and JavaScript, we call catch with a callback to catch errors.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.