TypeScript中如何判断异常是否为FirebaseError/FirebaseAuthError
如何在TypeScript中正确判断Firebase Auth抛出的异常
核心方案:通过错误码识别,而非依赖内部错误类
Firebase Admin并未将FirebaseAuthError这类内部错误类对外暴露,直接导入会触发导出路径错误。官方推荐的可靠方式是利用错误对象的code属性来判断——所有Firebase Auth抛出的错误,其code都会以auth/为前缀,比如auth/email-already-exists、auth/invalid-email等。
具体实现代码
import { getAuth } from "firebase-admin/auth"; import admin from "firebase-admin"; // 初始化Firebase Admin(未初始化时执行) if (!admin.apps.length) { admin.initializeApp(); } async function createUser(email: string, password: string) { try { const auth = getAuth(); return await auth.createUser({ email, password }); } catch (error) { // 先判断是否为带code属性的对象 if (typeof error === 'object' && error !== null && 'code' in error) { const fbError = error as { code: string; message: string }; // 筛选Auth类错误 if (fbError.code.startsWith('auth/')) { // 根据具体错误码处理 switch (fbError.code) { case 'auth/email-already-exists': console.error('该邮箱已被注册'); break; case 'auth/invalid-email': console.error('邮箱格式不符合要求'); break; case 'auth/weak-password': console.error('密码强度不足,需至少6位字符'); break; default: console.error('Firebase Auth错误:', fbError.code, fbError.message); } } else { console.error('Firebase其他服务错误:', fbError.code); } } else { console.error('非Firebase类型错误:', error); } // 可根据需求选择重新抛出错误或返回处理结果 throw error; } }
类型安全优化:自定义类型守卫
如果需要更严谨的类型检查,可以写一个类型守卫函数,明确判断是否为Firebase Auth错误:
function isFirebaseAuthError(error: unknown): error is { code: string; message: string } { return ( typeof error === 'object' && error !== null && 'code' in error && typeof (error as { code: unknown }).code === 'string' && (error as { code: string }).code.startsWith('auth/') ); } // 在catch块中使用 catch (error) { if (isFirebaseAuthError(error)) { // 这里error会被TS推断为Auth错误类型 switch (error.code) { // 处理具体错误 } } }
内容的提问来源于stack exchange,提问作者Lappesson
相关产品推荐
相关产品推荐

