简体   繁体   中英

Error handling when retrieving data from API

With this function I get weather data from API. How can I handle errors that occur when searching with a name of a city that does not exist or enter blank? I'm trying with try/catch but it doesn't work:(

response.data.name - is the name of the location

const searchLocation = (event) => {
if (event.key === 'Enter') {
  try {
    axios.get(`https://api.openweathermap.org/data/2.5/weather? 
    &q=${location}&appid=${API_KEY}&units=${metric_units}`).then((response) => {
      if (response.data.name) {
        console.log(response.data.name)
        setData(response.data)
      }
      
      })
      setLocation('')
  } catch (e) {
    console.log(e.message)
  }
}

}

You can do like this

const searchLocation = (event) => {
if (event.key === 'Enter') {
  axios.get(`https://api.openweathermap.org/data/2.5/weather? 
    &q=${location}&appid=${API_KEY}&units=${metric_units}`)
  .then(function (response) {
    if (response.data.name) {
        console.log(response.data.name)
        setData(response.data)
      }
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {  // final block is optional
    // always executed
  });
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM