Handle Axios errors and log error message from API

Advertisements

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.

>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;
  // ...

Leave a ReplyCancel reply