如何正确导入Firebase v9 JS SDK的AuthError对象并实现错误类型判断?
问题根因
Firebase Auth 导出的AuthError是仅存在于TypeScript编译阶段的接口类型,没有对应的运行时类实现,编译后接口会被完全擦除,因此e instanceof AuthError的判断在运行时完全不生效。
正确处理方案
方案1:使用官方提供的isAuthError类型守卫(推荐)
firebase/auth模块同时导出了运行时可用的isAuthError工具函数,专门用于判断捕获的错误是否为Auth相关错误,还能自动完成TypeScript类型收缩:
import { updatePassword, AuthError, isAuthError } from 'firebase/auth'; // 业务逻辑 try { await updatePassword(user, password); } catch (e) { if (isAuthError(e)) { // 此处e会被自动推导为AuthError类型,可直接访问code、message等属性 setErrorMessage(e.message); // 也可以根据错误码做细分处理,例如: // if (e.code === 'auth/weak-password') { // setErrorMessage('密码强度不足,请设置至少6位密码') // } } else { // 处理非Auth类型的其他错误 setErrorMessage('操作失败,请稍后重试') } }
方案2:手动判断错误特征(适合不需要类型推导的场景)
如果不想引入额外的工具函数,也可以通过Auth错误的固定特征判断:所有Firebase Auth抛出的错误都带有code属性,且值均以auth/为前缀:
import type { AuthError } from 'firebase/auth'; try { await updatePassword(user, password); } catch (e: unknown) { if ( typeof e === 'object' && e !== null && 'code' in e && typeof (e as {code: string}).code === 'string' && (e as {code: string}).code.startsWith('auth/') ) { const authError = e as AuthError; setErrorMessage(authError.message); } }
内容的提问来源于stack exchange,提问作者Charming Robot
相关产品推荐
相关产品推荐

