写有条件的“找不到城市”错误

问题描述

我正在使用openweathermap研究和构建一个项目的天气日志应用程序。

当我编写一个不属于我的API国家的邮政编码时,控制台会记录“ cod:404消息:找不到城市”,但是我不知道如何向用户显示。我知道我需要在postData代码之前写一个带有警告的条件(邮政编码错误!),但是我被困在这里...

function action(e){
    const postalCode = document.getElementById('zip').value;
    const feelings = document.getElementById('feelings').value;
    console.log(newDate);
 
    getTemp(baseUrl,postalCode,apiKey)
    .then(function (data){
         if(/*Message error*/){
            alert('Wrong zip code,try again!');
        }
        //Route
        postData('http://localhost:8000/addData',{ date: newDate,temp: data.main.temp,feel: feelings})
    .then(function(){
        //User Interface
        updateUI()
        })    
    })
}

enter image description here

解决方法

您可以这样使用:

getTemp(baseUrl,postalCode,apiKey)
.catch(function (error){
    alert('Wrong zip code,try again!');
    console.log(error);
})
.then((data) => {
    postData('http://localhost:8000/addData',{ date: newDate,temp: data.main.temp,feel: feelings})
      .then(function(){
        //User Interface
        updateUI()
    })    
})
,

由于响应是包含codmessage的对象,因此您可以检查if (data.cod === 404) {
然后显示您的警报。
请注意,您需要return;或将postData放在else中,否则在警报显示后仍将执行

@ Yehr59的答案存在问题,就是getTemp可能不会引发错误,因此不会到达.catch函数。因此,您可以在.then中执行上面在此答案中提到的检查。

您将遇到这样的情况:

getTemp(baseUrl,apiKey)
    .then(function (data){
         if(String(data.cod) === '404'){
            alert('Wrong zip code,try again!');
        } else {
            //Route
            postData('http://localhost:8000/addData',feel: feelings})
        }

我也将data.cod包裹在String周围,因此它始终是一个字符串。我们无法比较

"404" === 404 // false

编辑:另一种方法是修改您的getTemp函数,使其在响应代码为404的情况下会throw错误,然后您便知道一旦调用.then即可成功,如果.catch被调用,您将处理一个错误