PnP JS中Overwrite:false场景下错误处理异常求助
问题:上传同名文件时无法返回指定错误提示
用户代码:
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"); }
问题描述:
设置Overwrite: false上传同名已存在文件时,期望抛出The filename already exists!错误,但实际总是触发catch块的something went wrong错误,如何修复?
修复方案
问题根源
- 原代码的
else分支逻辑完全错误:它是在文件大小超过1048字节时触发,和文件是否重名没有任何关系,属于逻辑混淆。 - 当
addUsingPath在Overwrite: false且文件已存在时,会主动抛出API错误,这个错误会被外层catch直接捕获,根本走不到else分支。
修正步骤
- 移除错误的
else分支逻辑,若需要判断文件大小超限,改为抛出对应提示。 - 在
catch块中识别SP API返回的文件已存在错误,针对性抛出指定提示;其他错误保留原有处理逻辑。
修正后代码
try { if (file.size <= 1048) { result = await sp.web.lists .getByTitle(documentLibraryTitle) .rootFolder.files.addUsingPath(fileNamePath, file, { Overwrite: false }); } else { // 若需要文件大小限制提示,可保留此分支 throw new Error('文件大小超过限制!'); } } catch (err) { // 根据SP API返回的错误消息判断是否为文件已存在 const isDuplicateError = err.message.includes('File already exists') || err.message.includes('文件已存在'); if (isDuplicateError) { throw new Error('The filename already exists!'); } // 匹配文件大小超限的错误 else if (err.message.includes('文件大小超过限制')) { throw err; } // 其他异常处理 else { console.error("something went wrong", err); throw new Error("something went wrong"); } }
说明
- SP API在文件已存在时抛出的错误消息,会根据环境语言不同有所差异(英文为
File already exists,中文为文件已存在),所以同时包含两种判断条件。 - 保留了文件大小判断的逻辑,若不需要该限制,可直接删除
if (file.size <= 1048)分支,直接执行上传逻辑。
内容的提问来源于stack exchange,提问作者MomoCodez
相关产品推荐
相关产品推荐

