
在使用javascript的fetch api进行网络请求时,开发者常常会遇到.catch()块未能捕获到http错误(例如404 not found、500 internal server error)的情况。这是因为fetch api的设计理念将网络错误(如断网、dns解析失败、跨域策略阻塞)与服务器返回的http错误响应区分开来。.catch()方法仅用于捕获前者,而对于后者,fetch api认为服务器已经成功响应,即使响应的状态码表示错误。
要正确处理HTTP错误,我们需要在Promise链中的第一个.then()块内显式检查Response对象的属性。Response对象提供了几个关键属性来判断请求的成功与否:
当response.ok为false时,我们应该手动抛出一个错误,这样这个错误才能被后续的.catch()块捕获并处理。
以下是一个基于用户提供的场景,演示如何正确处理Fetch API错误的示例代码。我们将改进原有的代码,使其能够有效捕获HTTP错误以及在请求前进行输入验证。
let searchBtn = document.getElementById("search-btn");
let countryInp = document.getElementById("country-inp");
let resultDiv = document.getElementById("result"); // 假设有一个用于显示结果的div
searchBtn.addEventListener("click", () => {
let countryName = countryInp.value.trim(); // 使用trim()去除首尾空格
// 1. 请求前的数据验证
if (countryName.length === 0) {
resultDiv.innerHTML = `<h3>输入框不能为空。</h3>`;
return; // 阻止API请求
}
let finalURL = `https://restcountries.com/v3.1/name/${countryName}?fullText=true`;
console.log(`请求URL: ${finalURL}`);
fetch(finalURL)
.then(response => {
// 2. 检查HTTP响应状态
if (!response.ok) {
// 如果响应状态不是2xx,则抛出错误
// 可以根据statusText或status code提供更具体的错误信息
const errorText = response.status === 404 ? "未找到该国家,请检查国家名称。" : `HTTP错误: ${response.status} ${response.statusText}`;
throw new Error(errorText);
}
return response.json(); // 解析JSON数据
})
.then(data => {
// 3. 成功处理数据
// 检查data是否为数组且有内容,以防API返回空数组或其他非预期格式
if (!Array.isArray(data) || data.length === 0) {
throw new Error("API返回数据格式异常或为空。");
}
const countryData = data[0];
resultDiv.innerHTML = `
<img src="${countryData.flags.svg}" class="flag-img">
<h2>${countryData.name.common}</h2>
<div class="wrapper">
<div class="data-wrapper">
<h4>首都:</h4>
<span>${countryData.capital[0]}</span>
</div>
</div>
<div class="wrapper">
<div class="data-wrapper">
<h4>所属洲:</h4>
<span>${countryData.continents[0]}</span>
</div>
</div>
<div class="wrapper">
<div class="data-wrapper">
<h4>货币:</h4>
<span>${Object.keys(countryData.currencies)[0]}</span>
</div>
</div>
`;
console.log(countryData);
})
.catch(error => {
// 4. 统一的错误捕获与显示
// 这里会捕获到网络错误、response.ok为false时抛出的错误以及数据解析错误
console.error("请求或处理数据时发生错误:", error);
resultDiv.innerHTML = `<h3>${error.message || "请求失败,请稍后再试。"}</h3>`;
});
});<div class="container">
<input type="text" id="country-inp" placeholder="输入国家名称..." value="United Kingdom">
<button id="search-btn">搜索</button>
<div id="result">
<!-- 结果将显示在这里 -->
</div>
</div>代码改进说明:
通过上述方法,我们可以构建一个更加健壮和用户友好的应用程序,有效处理Fetch API请求中可能出现的各种错误情况。
以上就是深入理解Fetch API错误处理:捕获HTTP状态码与网络异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号