我的代码是一个简单的获取示例,当提供了正确的资源URL时,该示例才起作用。但是,当我拼写错误的资源名称时,我期望该错误被捕获在catch块中,但是那没有发生。控制台记录错误 “无法加载资源:服务器响应状态为404(未找到)
我的代码是
fetch('coffee.jpg')
.then(response => response.blob())
.then(blob => {
let myURL = URL.createObjectURL(blob);
let img = document.createElement('img');
img.src = myURL;
document.body.appendChild(img);
})
.catch(err => {
console.log(" Error fetching file - " + err.message);
});
答案 0 :(得分:2)
您可以添加这样的错误处理程序中间件:
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch('coffee.jpg')
.then(handleErrors)
.then(response => response.blob())
.then(blob => {
let myURL = URL.createObjectURL(blob);
let img = document.createElement('img');
img.src = myURL;
document.body.appendChild(img);
})
.catch(err => {
console.log(" Error fetching file - " + err.message);
});