Angular 9中async-await抛错出现Uncaught (in promise) Error的解决方法
问题根因
你遇到的Uncaught (in promise)报错,本质是异步逻辑抛出的错误没有被捕获:你在.then()回调的异步函数内抛出异常,会将.then()返回的Promise标记为拒绝状态,但你没有为这个Promise添加错误捕获处理,因此浏览器抛出未捕获异常。
正确实现方式
方案1:全链路async/await+try/catch(更推荐)
首先改造校验函数,将其改为async函数,统一用await处理异步逻辑:
// 校验上传的PDF文件页数不超过5 static async validatePdfFile(event: any): Promise<void> { const file = event.target.files[0]; const buff = await file.arrayBuffer(); const fileUint8Array = new Uint8Array(buff); const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false}); const totalPages = pdfDoc.getPageCount(); if(totalPages > 5) { throw new Error('File must be less than 5 pages.'); } }
调用校验函数时,通过try/catch捕获异步抛出的错误:
// Angular组件内上传事件逻辑示例 async onFileChange(event: any) { try { await 你的工具类名.validatePdfFile(event); // 校验通过,执行后续上传流程 } catch (err) { // 捕获错误,做用户提示或其他处理 console.error('校验失败:', err.message); // 例如用Angular组件提示:this.snackBar.open(err.message, '关闭', {duration: 3000}) } }
方案2:在Promise链末尾加catch处理
如果不想改动现有调用模式,可以直接在原有Promise链末尾添加catch捕获错误:
static validatePdfFile(event: any, onError?: (errMsg: string) => void) { const file = event.target.files[0]; file.arrayBuffer().then(async buff => { let fileUint8Array = new Uint8Array(buff); const pdfDoc = await PDFDocument.load(fileUint8Array, {updateMetadata: false}); const totalPages = pdfDoc.getPageCount(); if(totalPages > 5) { throw new Error('File must be less than 5 pages.'); } }).catch(err => { // 错误交由传入的回调处理,避免未捕获异常 if(onError) onError(err.message); }); }
调用示例:
onFileChange(event: any) { 你的工具类名.validatePdfFile(event, (errMsg) => { console.error('校验失败:', errMsg); // 提示用户校验失败 }) }
核心规则说明
- 所有
async函数执行后都会返回Promise对象,函数内部抛出的错误会作为该Promise的拒绝原因 - 所有状态为拒绝的Promise,必须通过
await+try/catch或者.catch()方法捕获错误,否则都会触发浏览器未捕获Promise异常 - 原始代码中
.then()的回调是async函数,它抛出的错误只会标记.then()返回的Promise为拒绝状态,没有捕获逻辑就会出现控制台报错
内容的提问来源于stack exchange,提问作者Durga Prasad
相关产品推荐
相关产品推荐

