You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 17:50:34