To handle errors in the code above, you can add a catch block after the then block, like this:

fetch(url)
  .then(response => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        function read() {
          reader.read().then(({done, value}) => {
            if (done) {
              controller.close();
              return;
            }
            controller.enqueue(value);
            read();
          });
        }
        read();
      },
    });
  })
  .catch(error => {
    console.error(error);
  });

This catch block will catch any errors that occur during the fetch or stream creation process. You can then handle the error however you like - logging it to the console, displaying an error message to the user, etc.

JavaScript Fetch API Error Handling with ReadableStream

原文地址: https://www.cveoy.top/t/topic/mDer 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录