如果大小写"overwrite: false"输入,则 PnP JS 处理错误



我的代码:

try{
if (file.size <= 1048) {
result = await sp.web.lists
.getByTitle(documentLibraryTitle)
.rootFolder.files.addUsingPath(fileNamePath, file, { Overwrite: false });
} 
else{
throw new Error(`The filename already exists!`);
}
} catch (err) {
console.error("something went wrong", err);
throw new Error("something went wrong");
}

我要做的是,如果大小写"覆盖:false">(=尝试上传同名的现有文件)…输入,我想在else括号内返回第一个错误。

而不是那样的结果,我总是在catch括号内得到错误。有人有办法解决这个问题吗?

我可以想到两个选择。第一个选项:在尝试覆盖该文件之前检查该文件是否存在,如果存在,则抛出错误。第二个选项:你分析pnpjs错误消息,如果是关于文件已经存在,抛出你的错误消息。

:

const exists = await sp.web.lists
.getByTitle(documentLibraryTitle).rootFolder.files
.getByName(fileNamePath) // or .getByUrl()
.exists();
if (exists) {
throw new Error(`The filename already exists!`);
}
// ... upload file like you do now ...

第二:

try {
await sp.web.lists
.getByTitle(documentLibraryTitle).rootFolder.files
.addUsingPath(fileNamePath, file, { Overwrite: false });
} catch (e) {
// see "error handling in pnpjs"
// https://pnp.github.io/pnpjs/concepts/error-handling/#reading-the-response
if (e.isHttpRequestError) {
// get the response
const data = await e.response.json();
// fetch error code
const code = typeof data["odata.error"] === "object" ? data["odata.error"].code : null;
// it's about overwrite
if (code === '-2130575257, Microsoft.SharePoint.SPException') {
throw new Error(`The filename already exists!`);
}
}
}
}

最新更新