如果用户在Weather Api搜索中输入了错误的城市名称,该如何使用try and catch?

时间:2019-05-24 08:16:00

标签: javascript error-handling weather-api

我希望用户输入无效的城市名称时弹出警报。

尝试使用if-else和try-catch方法,但不起作用。我正在使用Weather API来获取天气和温度。

const getWeather = () => {
  let cityName = $("#cityName").val();
  let apiCall = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&mode=json&units=metric&appid=${
    CONSTANTS.appId
  }`;
  $.getJSON(apiCall, weatherData => {
    let cityName = weatherData.name;
    let countryName = weatherData.sys.country;
    let description = weatherData.weather[0].description;
    let tempMin = weatherData.main.temp_min;
    let tempMax = weatherData.main.temp_max;
    $("#city").text(cityName);
    $("#detail").text(description);
    $("#country").text(countryName);
    $("#mintemp").html(`Minimum: ${tempMin}<span>&#8451;</span>`);
    $("#maxtemp").html(`Maximum: ${tempMax}<span>&#8451;</span>`);
  });
};

每当输入无效输入时,我都会在控制台中收到此消息。

GET http://api.openweathermap.org/data/2.5/weather?q=sdx&mode=json&units=metric&appid=d568dc579415266146ede4b4f9de029b 404 (Not Found)    
jquery-3.4.1.js:9837 

我不希望出现错误,而是使用错误来显示一条消息,指出无效的用户输入。

整个代码链接为https://github.com/Shefali-Upadhyay/weather-app

1 个答案:

答案 0 :(得分:0)

在这种情况下,您不需要with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) for epoch_i in range(epochs): for batch_i in range(number_of_batches): batch_data = getBatch(shuffled_data, batch_i, batch_size) sess.run(optimizer, feed_dict={x1: batch_data[:,:,0], X: batch_data}) train_loss = sess.run(loss, feed_dict={x1: aug_data[:,:,0], X: aug_data}) print(epoch_i, train_loss) 块,因为jQuery为您处理了所有事情,但是您需要嗅探HTTP状态代码。不要使用try...catch,而要使用$.getJSON()

如果您仍然想使用$.ajax(),则可以通过以下方式使用$.getJSON()链接方法:

.fail()