You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中Fetch API的catch无法捕获异常问题求助

Fetch的catch方法无法捕获异常的问题解决

问题原因

Fetch API 的.catch()只在网络请求彻底失败(如断网、域名无法解析)时触发。像404、500这类HTTP错误状态码,Fetch会判定请求已完成,不会自动进入catch块,而是继续执行后续.then(),这就是你的代码无法捕获404错误的核心原因。

另外你的代码还有两处细节错误:

  • 拼写错误:countryName.lengh 应为 countryName.length,导致空输入判断失效
  • 未获取result元素,直接赋值innerHTML会引发未定义错误

修复后的代码

<button id="search-btn">Search</button>
<input id="country-inp" value="United Kingdom"></input>
<!-- 补充result元素用于展示提示 -->
<div id="result"></div>
let searchBtn = document.getElementById("search-btn");
let countryInp = document.getElementById("country-inp");
// 先获取result元素
let result = document.getElementById("result");

searchBtn.addEventListener("click", () => {
    let countryName = countryInp.value.trim(); // 去除输入首尾空格
    let finalURL = `https://restcountries.com/v3.1/name/${countryName}?fullText=true`;
    console.log(finalURL);

    fetch(finalURL)
    .then((response) => {
        // 检查响应状态,非成功状态主动抛出错误
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log(data[0]);
        console.log(data[0].capital[0]);
        console.log(data[0].flags.svg);
        console.log(data[0].name.common);
        console.log(data[0].continents[0]);
        console.log(Object.keys(data[0].currencies)[0]);
        // 成功时清空提示或展示数据
        result.innerHTML = "";
    })
    .catch((error) => {
        console.error(error);
        if (countryName.length === 0) {
            result.innerHTML = `<h3>The input field cannot be empty</h3>`;
        } else {
            result.innerHTML = `<h3>Please enter a valid country name.</h3>`;
        }
    });
});

关键修改说明

  1. 主动抛出HTTP错误:在第一个.then()中通过response.ok判断请求是否成功,若失败则抛出错误,强制进入.catch()处理。
  2. 修正拼写错误:将lengh改为length,确保空输入的判断逻辑生效。
  3. 获取result元素:添加DOM元素获取,避免赋值innerHTML时出现未定义错误。
  4. 输入去重空格:使用trim()处理输入值,避免用户输入空格导致的无效请求。

内容的提问来源于stack exchange,提问作者Megan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:25:36