Javascript 承诺链中的捕获处理程序未捕获错误
我的代码是一个简单的获取示例,当提供了正确的资源URL时,它就会工作。但是,当我拼错资源名时,我希望错误会被捕获到catch块中,但事实并非如此。控制台记录了一个错误 “加载资源失败:服务器响应状态为404(未找到) 我的代码是Javascript 承诺链中的捕获处理程序未捕获错误,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,我的代码是一个简单的获取示例,当提供了正确的资源URL时,它就会工作。但是,当我拼错资源名时,我希望错误会被捕获到catch块中,但事实并非如此。控制台记录了一个错误 “加载资源失败:服务器响应状态为404(未找到) 我的代码是 fetch('coffee.jpg') .then(response => response.blob()) .then(blob => {
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);
});
fetch不会拒绝非2xx状态。在尝试访问正文之前检查响应的状态。很高兴它有帮助。请不要忘记将答案标记为5分钟后,以帮助将来的用户。谢谢!