My Code:
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");
}
What I'm trying to do is, if the case "Overwrite:false" (=Trying to upload an existing File with same Name) ...enters, i want to return the first error inside the else brackets.
Instead of that as result i always get the error inside the catch brackets. Anyone have an idea to fix this behaving?
I could think of two options. First option: you check that the file exists before trying to overwrite it, and if it does, then throw your error. Second option: you analyze the pnpjs error message, and if is about file being already there, throw your error message.
First:
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 ...
Second:
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!`);
}
}
}
}