【问题标题】:Error in showing error for openweathermap API显示 openweathermap API 错误时出错
【发布时间】:2017-02-01 10:25:12
【问题描述】:

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

无法读取未定义的属性“消息”

我的 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);
        });
    }
}

反应文件:

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

【问题讨论】:

  • @JaromandaX 不起作用:(
  • @JaromandaX 同样的错误
  • @JaromandaX 使用 chrome 最新版本。也更改为 return new Error(res.message); 在控制台中出现 2 个错误:502 (Bad Gateway) 和``未捕获(承诺)错误:对象作为 React 子项无效(发现:错误:请求失败,状态码为 502)。如果您打算渲染一组子对象,请改用数组或使用 React 附加组件中的 createFragment(object) 包装对象。检查WeatherMessage的渲染方法。
  • @JaromandaX 相同的初始错误 :(
  • 您需要阅读有关错误的documentation for axios 以及有关响应格式的documentation for openweathermap。虽然它确实没有提及消息,但消息至少存在于错误中 - 顺便说一下,错误处理程序中将是 res.response.data.message

标签: javascript reactjs error-handling react-router openweathermap


【解决方案1】:

这是您的代码的一个版本,它可以在没有任何未处理错误的情况下运行 - 基于 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;
        });
    }
}

反应文件:

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

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

【讨论】:

  • 是的,投掷看起来很奇怪,但技术很好,而且很有效。 tnx 很多!
猜你喜欢
  • 2016-05-06
  • 2018-06-05
  • 2016-01-10
  • 2021-09-18
  • 2019-10-15
  • 2020-11-15
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多