【问题标题】:Unable to handle 404 error in axios with try and catch无法使用 try 和 catch 处理 axios 中的 404 错误
【发布时间】:2022-01-05 05:29:03
【问题描述】:

我一直在尝试构建一个天气应用程序,但在验证 http 状态时遇到了一些麻烦,以防用户自愿插入一个不存在的城市名称,或者用户在输入字段中输入错误。

唯一的问题是我找不到在 axios 承诺中插入 status !== 200 的方法。

200 状态工作得很好,但 404 不行。我确信承诺中的某个地方有错误,但我无法找到解决方法。

此外,当我在控制台记录错误时,它会显示以下消息:

console.log 中的错误

Uncaught (in promise) Error: Request failed with status code 404
    at e.exports (createError.js:16)
    at e.exports (settle.js:17)
    at XMLHttpRequest.E (xhr.js:66)

Javascript

try{            
            axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}`).then(
                
            async response => {
                
            let data = await response.data

            if (response.status !== 200) {
            
                throw new Error(response.status);
            
                } else {
            
            console.log(data)
            document.getElementById('hum').textContent = data.main.humidity;
            document.getElementById('feels-like').textContent = data.main.feels_like;
                }}
        )
        
        } catch(error) {
            if (response.status === 404) {
                console.log(`Err: ${error}`);
                throw err;
            }
                   
        
        };

非常感谢任何建议。谢谢!

【问题讨论】:

    标签: api promise axios http-status-code-404


    【解决方案1】:

    您的try/catch 不会捕获您在.then() 处理程序中抛出的拒绝,也不会捕获axios 本身抛出的任何拒绝,除非您await axios 调用。

    try {
        await axios.get(...).then(...)
    } catch(e) {
        // now you can catch a rejection
    }
    

    当然,您也可以改用.catch()。


    风格上,不建议在这里混用try/catch、await和.then()。你应该这样做:

    try {
        const response = await axios.get(...);
        // process response here, including throw
    } catch(e) {
        // here you can catch a rejection, either from axios
        // directly or from throwing in the processing
    }
    

    或:

    axios.get(...).then(...).catch(...)
    

    【讨论】:

    • 非常感谢。错误在承诺中。现在可以了。
    • @Mark88 - 由于您可能是这里的新手,如果这回答了您的问题,您可以通过单击答案左侧的复选标记向社区表明这一点。这也将为您在此处遵循正确的程序赢得一些声誉积分。
    猜你喜欢
    • 2022-11-20
    • 2022-06-16
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 2018-10-29
    相关资源
    最近更新 更多