在承诺链中捕获处理程序未捕获错误

时间:2020-02-22 08:33:41

标签: javascript promise es6-promise

我的代码是一个简单的获取示例,当提供了正确的资源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);
                });

1 个答案:

答案 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);
  });