【问题标题】:Unable to catch error while using fetch API使用 fetch API 时无法捕获错误
【发布时间】:2023-01-11 15:41:54
【问题描述】:

我是编码新手,正在尝试实现下载进度。下面是我的代码。

let btn = document.querySelector("#img");
btn.addEventListener("click", loadimage);
function loadimage() {
  fetch("https://reqres.in/invalid-url")
    .then(async (res) => {
      let contLength = res.headers.get("content-length");
      let reader = res.body.getReader();
      let downloaded_data = 0; 
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          console.log("completed");
          break;
        }
        downloaded_data += value.length;
        console.log(downloaded_data);
      }
    })
    .catch(function (err) {
      console.log("catch block");
      console.log(err);
    });
}`  

` 这是我得到的错误。(没有被 catch 块捕获)

`GET https://reqres.in/invalid-url 404`
`6939`
`completed`

为什么尽管有错误,then 块中的函数仍被调用。 我尝试了不同的 API,但结果都一样

【问题讨论】:

    标签: javascript error-handling fetch


    【解决方案1】:

    使用 await 代替它并尝试像这样编写代码:

    // Step 1: start the fetch and obtain a reader
    let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');
    
    const reader = response.body.getReader();
    
    // Step 2: get total length
    const contentLength = +response.headers.get('Content-Length');
    
    // Step 3: read the data
    let receivedLength = 0; // received that many bytes at the moment
    let chunks = []; // array of received binary chunks (comprises the body)
    while(true) {
      const {done, value} = await reader.read();
    
      if (done) {
        break;
      }
    
      chunks.push(value);
      receivedLength += value.length;
    
      console.log(`Received ${receivedLength} of ${contentLength}`)
    }
    
    // Step 4: concatenate chunks into single Uint8Array
    let chunksAll = new Uint8Array(receivedLength); // (4.1)
    let position = 0;
    for(let chunk of chunks) {
      chunksAll.set(chunk, position); // (4.2)
      position += chunk.length;
    }
    
    // Step 5: decode into a string
    let result = new TextDecoder("utf-8").decode(chunksAll);
    
    // We're done!
    let commits = JSON.parse(result);
    alert(commits[0].author.login);
    

    参考:https://javascript.info/fetch-progress

    【讨论】:

      【解决方案2】:

      你必须检查then中的response.ok

      https://stackoverflow.com/a/38236296/16906055

      【讨论】:

        猜你喜欢
        • 2021-08-07
        • 2019-05-22
        • 1970-01-01
        • 2021-03-08
        • 2018-09-28
        • 2023-03-10
        • 1970-01-01
        • 2021-09-03
        • 2022-10-12
        相关资源
        最近更新 更多