【问题标题】:proper error handling in an asynchronous async/await function [duplicate]异步 async/await 函数中的正确错误处理 [重复]
【发布时间】:2020-05-15 10:42:36
【问题描述】:

我对在 javascript 中处理 async 函数中的错误的正确方法有点困惑。

async function getWeatherAW(woeid) {
        try {
            const result = await fetch(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${woeid}/`);
            const data = await result.json();
            const tomorrow = data.consolidated_weather[1];
            return data;
        } catch(error) {
            console.log(`Error catch-Statement: ${error}`);
        }
    }

const wrongData = 3442;
getWeatherAW(wrongData)
.then(data => {
    console.log(data);
})
.catch(error => {
    console.log(`Error .catch()-Statement: ${error}`);
})

这段代码最终给出了这个result。我很好奇为什么即使触发了catch语句,控制台也会打印出404错误..

不从async 函数返回结果而是在函数中继续执行会更好吗?我的意思是当首先发生错误时,then块中的数据似乎是未定义的。如果我需要更频繁地调用该函数,我并不总是需要编写then和catch,对吧?

提前致谢!

【问题讨论】:

  • "发生错误时,then 块中的数据似乎未定义" - 那是因为您的 try/catch 正在处理异常,然后返回undefined。你也可以返回其他东西。但是拥有undefined 似乎不是很有用,每次都需要if (data !== undefined),拒绝承诺并正确处理错误似乎更好。
  • 请参阅this thread,了解来自 fetch 的浏览器日志记录错误。

标签: javascript async-await


【解决方案1】:

无论错误是否得到处理,控制台都会为所有失败的请求打印 404 消息。

它是一种调试帮助,显示请求失败,而不是表示未处理失败。

【讨论】:

  • 感谢@SLaks。所以没什么好担心的,错误会被捕获吗? :D
【解决方案2】:

错误提示cannot read property '1' of undefined

async function getWeatherAW(woeid) {
        try {
            const result = await fetch(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${woeid}/`);
            const data = await result.json();
            const tomorrow = data.consolidated_weather[1]; <----- this is undefined
            return data;
        } catch(error) {
            console.log(`Error catch-Statement: ${error}`);
        }
    }

const wrongData = 3442;
getWeatherAW(wrongData)
.then(data => {
    console.log(data);
})
.catch(error => {
    console.log(`Error .catch()-Statement: ${error}`);
})

我的猜测是 tomorrow 在数据初始化之前进行初始化 - 或者 data 没有密钥 consolidate_weather

fetch.then() 可能会得到你想要的结果


let tomorrow;
return fetch(url).then((result) => {
     const data = JSON.parse(result);
     tomorrow = data.consolidated_weather[1];
     return data;
}, (error) => {
    console.log(`Error .catch()-Statement: ${error}`);
})

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2013-10-02
    • 2018-04-13
    • 2021-08-08
    • 2020-10-03
    • 2019-02-14
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多