我正在使用 Nextjs(无关但仍然)。 我尝试使用 trycatch 块但无法捕获上述错误。有没有办法捕获这个错误。如果是这样怎么办。
Try/catch 块无法捕获此错误。
当由于某种原因 url 为
invalid (meaning the object to which the url is pointing doesn't exist or has been deleted)
时会发生这种情况
以下是代码:-
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);
}
}
你可以尝试一下。
可选链接 (?.):- 可用于安全地访问可能未定义的对象的嵌套属性。
const url = window?.URL?.createObjectURL(blob);