Monday 14 August 2023

How to catch the following error "Failed to execute 'createObjectURL' on 'URL':"

I am using Nextjs (irrelevant but still). I have tried using the trycatch block and unable to catch the above error. Is there a way to catch this error. If so how can it be done.

Try/catch block cannot catch this error.

This happens when the url is invalid (meaning the object to which the url is pointing doesn't exist or has been deleted) for some reason

Following is the code :-

function saveOrOpenBlob(url, blobName, changeName) {
    try {
      if (timer) {
        clearTimeout(timer);
      }
      let blob;
      let xmlHTTP = new XMLHttpRequest();
      xmlHTTP.open("GET", url, true);
      xmlHTTP.responseType = "arraybuffer";
      xmlHTTP.onload = function (e) {
        blob = new Blob([this.response]);
      };
      xmlHTTP.onprogress = function (pr) {
        //pr.loaded - current state
        //pr.total  - max
        setDownloadProgress((pr.loaded / pr.total) * 100);
      };
      xmlHTTP.onloadend = function (e) {
        let fileName = blobName;
        let tempEl = document.createElement("a");
        document.body.appendChild(tempEl);
        tempEl.style = "display: none";
        url = window.URL.createObjectURL(blob);
        tempEl.href = url;
        if (changeName) {
          tempEl.download = fileName;
        }
        tempEl.click();
        window.URL.revokeObjectURL(url);
        // For the progressbar to be visible for more duration
        timer = setTimeout(() => {
          setDownloading(false);
          setDownloadProgress(0);
        }, 1000);
      };
      xmlHTTP.send();
    } catch (error) {
      setDownloading(false);
      setDownloadProgress(0);
      setAlert("An error occurred while downloading the file", "error", 4000);
    }
  }


from How to catch the following error "Failed to execute 'createObjectURL' on 'URL':"

No comments:

Post a Comment