Handling HTTP Errors using Javascript

Handling HTTP Errors using Javascript

What's more frustrating than seeing Request failed with status code 400 returned from error.message?

Screenshot from 2021-03-14 12-45-21.png

On the surface, it makes sense that console.log(error.message) should display the error message returned from the backend, but it doesn't. It turns out, the custom message returned from the backend lives in the error response. Specifically, in error.response.data.message.

const fetchData = async () => {
  try {
    const { data } = await axios.get("/some-data");
    console.log(data);
  } catch (error) {
    console.log(error.response.data.message);
  }
};

Analyzing error.response.data.message shows that it follows the same way of accessing data in the try block. The only difference being the error appended to the response object.

You can still access the error message with .then and .catch.

const fetchData = () => {
  axios
    .get("/some-data")
    .then(({ data }) => {
      console.log(data);
    })
    .catch((error) => {
      console.log(error.response.data.message);
    });
};

If you want to get facier, you can destructure response directly in the catch sub-block.

    .catch(({response}) => {
      console.log(response.data.message);
    });

Thanks for stopping by. Adios ✌🏾🧑.

Credits

  1. Website vector created by stories - www.freepik.com
Β