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

try块内if语句抛出指定errorcode无效,如何抛出目标错误码?

如何在指定条件下抛出特定错误码而非统一的catch错误?

你的问题核心是:try块内抛出的121错误被同级的catch块直接捕获,导致被替换成100错误抛出。要实现抛出指定的121错误,有两种常见处理方式:

方案一:在catch块中过滤错误,保留特定错误码

修改catch逻辑,只对非121的错误抛出100,原121错误直接重新抛出:

private terminateUser = async (req): Promise<any> => {
  try {
    if(req.oper === 'cancel'){
      if(!('termStat' in corporate.data)){
        console.log('here');
        throw new ServerError({ errorcode: 121 });
      } else {
        const reqbody = this.generateReqbody(req); // 建议添加变量声明避免隐式全局变量
      }
    }
    return await Promise.resolve(this.config.message);
  } catch(err) {
    // 仅当错误不是121的ServerError时,抛出100错误
    if (err instanceof ServerError && err.errorcode !== 121) {
      throw new ServerError({ errorcode: 100 });
    }
    // 其他情况(包括121错误)直接抛出原错误
    throw err;
  }
}

方案二:缩小try块范围,前置校验错误不进入catch

如果termStat的校验属于前置逻辑,不需要进入后续业务代码的try/catch,可以把校验逻辑移到try块外:

private terminateUser = async (req): Promise<any> => {
  if(req.oper === 'cancel'){
    if(!('termStat' in corporate.data)){
      console.log('here');
      throw new ServerError({ errorcode: 121 }); // 这里抛出的错误不会被下面的try/catch捕获
    } else {
      const reqbody = this.generateReqbody(req); // 建议添加变量声明避免隐式全局变量
    }
  }

  // 仅对后续业务逻辑做错误捕获
  try {
    return await Promise.resolve(this.config.message);
  } catch(err) {
    throw new ServerError({ errorcode: 100 });
  }
}

两种方案选哪种取决于你的业务逻辑:如果121错误需要和其他错误区分处理,用方案一;如果前置校验错误不需要进入后续逻辑的错误处理,用方案二更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:48:35