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

如何优化处理消息展示场景下的过长IF ELSE判断逻辑

现有逻辑优化方案

方案1:直接利用规律简化(适配当前场景)

你当前的响应码和翻译key存在明确对应规则:vxxx 对应 code_xxx,完全不需要写200条if判断,直接做字符串替换即可:

private getQuotCollection(id: number) {
  this._spin.show();
  this._user.getApi(this.quotCollectionURL + id).subscribe(
    (res) => {
      this._spin.hide();
      if (res.status.code === 0) {
        this.respCode = this.quoteCollection?.respCode;
        if (this.respCode?.startsWith('v')) {
          // 直接替换前缀生成翻译key,无需逐条判断
          const translateKey = `code_${this.respCode.slice(1)}`;
          this.respDesc = this.translate.instant(translateKey);
        } else {
          // 异常情况兜底
          this.respDesc = '未知错误';
        }
      }
    }
  )
}

方案2:抽离公共逻辑(适配无统一规则的通用场景)

如果后续存在不符合上述规则的特殊响应码,可以把判断逻辑抽成独立工具方法复用:

第一步:新建工具文件 src/utils/resp-code.ts

// 特殊响应码映射表,仅存不符合通用规则的配置即可
const SPECIAL_RESP_MAP: Record<string, string> = {
  // 举个特殊配置示例:比如v201对应的翻译key不是code_201的情况
  'v201': 'custom_system_busy',
  'v202': 'custom_permission_deny'
}

/**
 * 统一获取响应码翻译文本
 * @param respCode 接口返回的响应码
 * @param translate i18n翻译实例
 * @param defaultDesc 兜底默认文本
 */
export function getRespTranslateDesc(
  respCode: string | undefined | null,
  translate: { instant: (key: string) => string },
  defaultDesc = '未知错误'
): string {
  if (!respCode) return defaultDesc;
  // 优先取特殊配置
  if (SPECIAL_RESP_MAP[respCode]) {
    return translate.instant(SPECIAL_RESP_MAP[respCode]);
  }
  // 符合通用规则走自动拼接逻辑
  if (respCode.startsWith('v')) {
    return translate.instant(`code_${respCode.slice(1)}`);
  }
  return defaultDesc;
}

第二步:业务代码中调用

// 顶部引入工具方法
import { getRespTranslateDesc } from 'src/utils/resp-code';

private getQuotCollection(id: number) {
  this._spin.show();
  this._user.getApi(this.quotCollectionURL + id).subscribe(
    (res) => {
      this._spin.hide();
      if (res.status.code === 0) {
        this.respCode = this.quoteCollection?.respCode;
        // 一行代码完成翻译逻辑
        this.respDesc = getRespTranslateDesc(this.respCode, this.translate);
      }
    }
  )
}

方案优势

  • 符合规则的新增响应码无需修改任何代码,自动适配
  • 特殊响应码仅需在映射表新增一条配置,无需堆砌if else
  • 逻辑抽离后全项目所有响应码翻译场景都可复用,无需重复写判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 21:54:05