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

JavaScript自定义AuthError类如何校验构造函数传入的错误码合法性

实现方案

核心思路是同时支持匹配AuthErrorCode的顶层键和内部code属性值,不需要手写冗余的switch case,两种实现方案如下:

推荐实现(预缓存映射,性能最优)

提前把两种可接受的code值存入Map做映射,实例化时直接查询即可,适合错误码数量多的场景:

// 你已定义的错误常量
const AuthErrorCode = {
  EMAIL_ALREADY_EXISTS: {
    code: "auth/email-already-exists",
    message: "Hello world!"
  },
  // ... 更多错误码
};

// 预生成双向映射表,支持通过顶层键、内部code两种方式查询配置
const authCodeLookupMap = new Map();
Object.entries(AuthErrorCode).forEach(([topLevelKey, config]) => {
  authCodeLookupMap.set(topLevelKey, config);
  authCodeLookupMap.set(config.code, config);
});

// 自定义错误类实现
class AuthError extends Error {
  constructor(code, message = undefined) {
    // 直接查映射表,匹配不到直接抛错
    const matchedConfig = authCodeLookupMap.get(code);
    if (!matchedConfig) {
      throw new Error(`Invalid AuthError code: ${code}, please pass a valid key or code value from AuthErrorCode`);
    }

    // 优先使用传入的自定义message,没有则用配置默认值
    const finalMessage = message ?? matchedConfig.message;
    super(finalMessage);

    Object.assign(this, {
      code: matchedConfig.code, // 最终code统一用配置里的标准值
      name: "AuthError",
    });
  }
}

简单实现(无需预缓存,适合错误码少的场景)

如果错误码数量很少,不想额外维护映射表,也可以每次实例化时动态校验:

class AuthError extends Error {
  constructor(code, message = undefined) {
    let matchedConfig = null;
    // 先匹配是否是顶层键
    if (AuthErrorCode.hasOwnProperty(code)) {
      matchedConfig = AuthErrorCode[code];
    } else {
      // 遍历匹配是否是内部code值
      for (const config of Object.values(AuthErrorCode)) {
        if (config.code === code) {
          matchedConfig = config;
          break;
        }
      }
    }

    if (!matchedConfig) {
      throw new Error(`Invalid AuthError code: ${code}`);
    }

    const finalMessage = message ?? matchedConfig.message;
    super(finalMessage);

    Object.assign(this, {
      code: matchedConfig.code,
      name: "AuthError",
    });
  }
}

效果验证

  • 合法调用均正常工作:
    // 传入顶层键,自定义message
    throw new AuthError("EMAIL_ALREADY_EXISTS", "自定义提示");
    // 传入内部code,用默认message
    throw new AuthError("auth/email-already-exists");
    
  • 非法调用直接抛出错误:
    // 不存在的code,直接抛出错误
    throw new AuthError("auth/some-invented-code", "Hello world!");
    

内容的提问来源于stack exchange,提问作者Raul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:24:05