承诺链中的 catch 处理程序未捕获错误
catch handler in promise chain not capturing the error
我的代码是一个简单的获取示例,它在提供正确的资源 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);
});
您可以像这样添加错误处理程序中间件:
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);
});
我的代码是一个简单的获取示例,它在提供正确的资源 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);
});
您可以像这样添加错误处理程序中间件:
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);
});