Firebase文档不存在时抛出的错误无法被catch捕获问题求助
问题排查结果
核心原因
async函数返回普通值(包括Error实例)时,会被包装为*成功状态(fulfilled)的Promise,只有主动throw抛出错误、或函数内部出现运行时异常,才会返回失败状态(rejected)*的Promise,进而被catch回调捕获。你当前代码中使用return new Error(...)返回错误,错误对象会作为成功返回值传入then回调,自然不会触发500状态码返回。
修复方案
修改addCustomerToStore方法内的错误抛出逻辑,将return改为throw即可:
class StoreGateway { async addCustomerToStore( customerId: string ) { const customer = await fb.customersCollection.doc(customerId).get(); if (customer.exists) { //do other stuff } else { console.log("customer didn't exist") // 替换return为throw,触发Promise rejected状态 throw new Error("customer didn't exist"); } } }
修改后原有调用逻辑无需调整,文档不存在的场景会自动进入catch分支返回500状态码。
内容的提问来源于stack exchange,提问作者radishhorse
相关产品推荐
相关产品推荐

