Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Handle Axios errors and log error message from API

I am making an HTTP request in Node.js using Axios to the WeatherStack API:

const axios = require("axios");

async function getWeather(city) {
  try {
    const res = await axios({
      method: "get",
      url: `http://api.weatherstack.com/current`,
      params: {
        access_key: "XXXXXXXXXXX",
        query: city,
        units: "m",
      },
      headers: {
        "Content-Type": "application/json",
      },
    });

    const temp = res.data.current.temperature;
    const precip = res.data.current.precip;
    const feels = res.data.current.feelslike;
    const desc = res.data.current.weather_descriptions[0];

    console.log(
      `${desc}. It is currently ${temp} degrees out. It feels like ${feels} degrees. There is ${precip}% chance of rain.`
    );
  } catch (error) {
    console.log(error);
  }
}

getWeather("helloworld")

When I call the function, I get an error:
TypeError: Cannot read properties of undefined (reading ‘temperature’)

But instead of this low-level error, I want to get the error message from the API and display it. In this case, "helloworld" is not a valid name. How to achieve this using Axios? I tried conditional logic in the catch block, but nothing worked. I was getting undefined when I log the error.response.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the documentation says, you’re receiving the expected response in res.data:

{
  success: false,
  error: {
    code: 101,
    type: 'missing_access_key',
    info: 'You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]'
  }
}

So, you can check an easy check here:

const res = await axios({
  method: "get",
  url: `http://api.weatherstack.com/current`,
  params: {
    access_key: "XXXXXXXXXXX",
    query: city,
    units: "m",
  },
  headers: {
    "Content-Type": "application/json",
  },
});

if (res.data.error) {
  // Manage your error
  console.log(res.data.error.code) // 101
  console.log(res.data.error.info) // Error description
} else {
  const temp = res.data.current.temperature;
  // ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading