javascript - 显示 openweathermap API 错误时出错

标签 javascript reactjs error-handling react-router openweathermap

我正在使用openweathermap.org我的 React 应用程序中的 api。它工作正常,但当用户输入错误的城市名称时不会显示错误。 有时也显示

cannot read property 'message' of undefined

我的 openweather.js

import axios from 'axios';

const weather_url = 'http://api.openweathermap.org/data/2.5/weather?appid=************&units=metric';

export default {
    getTemp(location){
        var encodedLocation = encodeURIComponent(location);
        var requrl = `${weather_url}&q=${encodedLocation}`;

        return axios.get(requrl).then(function(res){
            if(res.data.cod && res.data.message){
                throw new Error(res.message);
            } else{
                 return res.data.main.temp;
            }
        },function(res){
            return new Error(res.data.message);
        });
    }
}

react 文件:

openWeatherMap.getTemp(location)
    .then(function(temp){
        that.setState({
            location:location,
            temp:temp,
            isLoading:false
        })
    },function(err){
        alert(err);
    });

最佳答案

这是一个没有任何未处理错误的代码版本 - 基于 axios documentationopenweathermap API documentation

openweather.js

import axios from 'axios';
const weather_url = 'http://api.openweathermap.org/data/2.5/weather?appid=************&units=metric';
export default {
    getTemp(location){
        var encodedLocation = encodeURIComponent(location);
        var requrl = `${weather_url}&q=${encodedLocation}`;
        return axios.get(requrl).then(res => {
            if (res.data.cod === 200){
                return JSON.stringify(res.data);//.data.main.temp;
            }
            throw res.data.cod;
        }, res => {
            throw (res && ((res.response && res.response.data && (res.response.data.message || res.response.data)) || (res.code))) || res;
        });
    }
}

react 文件:

openWeatherMap.getTemp(location).then(function(temp){
    that.setState({
        location:location,
        temp:temp,
        isLoading:false
    })
},function(err){
    alert(err);
});

那个抛出看起来很丑陋,但我不知道你可能会遇到什么类型的错误......这种丑陋是基于我可以通过各种方式“强制”的错误

关于javascript - 显示 openweathermap API 错误时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977279/

相关文章:

ios - 在代码中使用导航 Controller 而不是rootviewcontroller

javascript - ReactJs:如何转义 <p> 包含来自 props 的数据渲染

asp.net - IIS 7错误代码

javascript - jQuery Ajax 获取数据语法错误,无法识别的表达式 :

javascript - 在列表中选择 AngularJS 复选框

reactjs - Craco 插件未加载

javascript - 基于另一个字段更新一个字段

c# - 错误处理超过重试次数 10

javascript - 表单提交后 Puppeteer 等待页面加载

javascript - 为什么 JSON.parse 的第二个参数叫做 “reviver” ?