Skip to content

Commit 37f7505

Browse files
tpfzCoda-bot
andcommitted
feat: [Coda] migrate fmt.Errorf to errorx error codes in evaluation module
(LogID: 202509241110360100911101341211FA3) Co-Authored-By: Coda <[email protected]>
1 parent 6d6b81c commit 37f7505

File tree

3 files changed

+146
-39
lines changed

3 files changed

+146
-39
lines changed

backend/modules/evaluation/application/evaluator_app.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1029,7 +1029,7 @@ func (e *EvaluatorHandlerImpl) transformURIsToURLs(ctx context.Context, inputFie
10291029

10301030
urlMap, err := e.fileProvider.MGetFileURL(ctx, uris)
10311031
if err != nil {
1032-
return fmt.Errorf("failed to get file URLs: %w", err)
1032+
return errorx.NewByCode(errno.FileURLRetrieveFailedCode, errorx.WithExtraMsg(err.Error()))
10331033
}
10341034

10351035
// 回填URL到原始数据
@@ -1193,7 +1193,7 @@ func (e *EvaluatorHandlerImpl) batchDebugWithConcurrency(ctx context.Context, ev
11931193
// 创建并发池,并发度为10
11941194
pool, err := goroutine.NewPool(10)
11951195
if err != nil {
1196-
return nil, fmt.Errorf("failed to create goroutine pool: %w", err)
1196+
return nil, errorx.NewByCode(errno.GoroutinePoolCreateFailedCode, errorx.WithExtraMsg(err.Error()))
11971197
}
11981198

11991199
// 初始化结果数组
@@ -1244,10 +1244,10 @@ func (e *EvaluatorHandlerImpl) batchDebugWithConcurrency(ctx context.Context, ev
12441244
// 执行所有任务,使用ExecAll确保单个失败不影响其他任务
12451245
err = pool.ExecAll(ctx)
12461246
if err != nil {
1247-
return nil, fmt.Errorf("failed to execute batch debug tasks: %w", err)
1247+
return nil, errorx.NewByCode(errno.BatchTaskExecutionFailedCode, errorx.WithExtraMsg(err.Error()))
12481248
}
12491249

12501250
return &evaluatorservice.BatchDebugEvaluatorResponse{
12511251
EvaluatorOutputData: results,
12521252
}, nil
1253-
}
1253+
}

backend/modules/evaluation/domain/service/evaluator_source_code_impl.go

Lines changed: 34 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// Copyright (c) 2025 coze-dev Authors
2-
// SPDX-License-Identifier: Apache-2.0
3-
2+
// SPDX-License-Identifier: Apache-2.0 return errorx.NewByCode(errno.RequiredFunctionNotFoundCode, errorx.WithExtraMsg("代码中必须定义 exec_evaluation 或 execEvaluation 函数。JavaScript 函数定义格式:function execEvaluation(turn, userInput, modelOutput, modelConfig, evaluatorConfig) { ... } 或 function exec_evaluation(turn, user_input, model_output, model_config, evaluator_config) { ... }"))
43
package service
54

65
import (
@@ -289,26 +288,26 @@ func (c *EvaluatorSourceCodeServiceImpl) prepareAndExecuteCode(ctx context.Conte
289288
// 1. 获取代码构建器
290289
codeBuilder, err := c.codeBuilderFactory.CreateBuilder(codeVersion.LanguageType)
291290
if err != nil {
292-
return "", nil, fmt.Errorf("failed to get code builder for language %s: %v", codeVersion.LanguageType, err)
291+
return "", nil, errorx.NewByCode(errno.CodeBuilderGetFailedCode, errorx.WithExtraMsg(fmt.Sprintf("language: %s, error: %v", codeVersion.LanguageType, err)))
293292
}
294293

295294
// 2. 构建代码
296295
code, err := codeBuilder.BuildCode(input, codeVersion)
297296
if err != nil {
298-
return "", nil, fmt.Errorf("failed to build code: %v", err)
297+
return "", nil, errorx.NewByCode(errno.CodeBuildFailedCode, errorx.WithExtraMsg(err.Error()))
299298
}
300299

301300
// 3. 获取Runtime
302301
runtime, err := c.runtimeManager.GetRuntime(codeVersion.LanguageType)
303302
if err != nil {
304-
return code, nil, fmt.Errorf("failed to get runtime for language %s: %v", codeVersion.LanguageType, err)
303+
return code, nil, errorx.NewByCode(errno.RuntimeGetFailedCode, errorx.WithExtraMsg(fmt.Sprintf("language: %s, error: %v", codeVersion.LanguageType, err)))
305304
}
306305

307306
// 4. 执行代码
308307
ext := c.buildExtParams(evaluator)
309308
result, err := runtime.RunCode(ctx, code, string(codeVersion.LanguageType), c.getTimeoutMS(), ext)
310309
if err != nil {
311-
return code, nil, fmt.Errorf("code execution failed: %v", err)
310+
return code, nil, errorx.NewByCode(errno.CodeExecutionFailedCode, errorx.WithExtraMsg(err.Error()))
312311
}
313312

314313
return code, result, nil
@@ -486,7 +485,7 @@ func (c *EvaluatorSourceCodeServiceImpl) PreHandle(ctx context.Context, evaluato
486485
func (c *EvaluatorSourceCodeServiceImpl) Validate(ctx context.Context, evaluator *entity.Evaluator) error {
487486
// 基础验证
488487
if evaluator.EvaluatorType != entity.EvaluatorTypeCode || evaluator.CodeEvaluatorVersion == nil {
489-
return fmt.Errorf("invalid evaluator type or code evaluator version is nil")
488+
return errorx.NewByCode(errno.InvalidEvaluatorConfigurationCode, errorx.WithExtraMsg("invalid evaluator type or code evaluator version is nil"))
490489
}
491490

492491
codeVersion := evaluator.CodeEvaluatorVersion
@@ -513,7 +512,7 @@ func (c *EvaluatorSourceCodeServiceImpl) Validate(ctx context.Context, evaluator
513512
case entity.LanguageTypeJS:
514513
return c.validateJavaScriptCode(ctx, evaluator, codeVersion)
515514
default:
516-
return fmt.Errorf("unsupported language type: %s", codeVersion.LanguageType)
515+
return errorx.NewByCode(errno.UnsupportedLanguageTypeCode, errorx.WithExtraMsg(fmt.Sprintf("language type: %s", codeVersion.LanguageType)))
517516
}
518517
}
519518

@@ -607,13 +606,13 @@ func (c *EvaluatorSourceCodeServiceImpl) parseSyntaxValidationStdoutJSON(stdout
607606
// 清理stdout,移除换行符和额外的空白字符
608607
stdout = strings.TrimSpace(stdout)
609608
if stdout == "" {
610-
return nil, fmt.Errorf("empty stdout")
609+
return nil, errorx.NewByCode(errno.ExecutionResultEmptyCode, errorx.WithExtraMsg("stdout is empty"))
611610
}
612611

613612
// 尝试解析JSON
614613
var result map[string]interface{}
615614
if err := json.Unmarshal([]byte(stdout), &result); err != nil {
616-
return nil, fmt.Errorf("failed to parse stdout JSON: %v", err)
615+
return nil, errorx.NewByCode(errno.ExecutionResultParseFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to parse stdout JSON: %v", err)))
617616
}
618617

619618
// 解码错误信息中的Unicode转义字符
@@ -631,13 +630,13 @@ func (c *EvaluatorSourceCodeServiceImpl) parseSyntaxValidationRetValJSON(retVal
631630
// 清理retVal,移除换行符和额外的空白字符
632631
retVal = strings.TrimSpace(retVal)
633632
if retVal == "" {
634-
return nil, fmt.Errorf("empty ret_val")
633+
return nil, errorx.NewByCode(errno.ExecutionResultEmptyCode, errorx.WithExtraMsg("ret_val is empty"))
635634
}
636635

637636
// 尝试解析JSON
638637
var result map[string]interface{}
639638
if err := json.Unmarshal([]byte(retVal), &result); err != nil {
640-
return nil, fmt.Errorf("failed to parse ret_val JSON: %v", err)
639+
return nil, errorx.NewByCode(errno.ExecutionResultParseFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to parse ret_val JSON: %v", err)))
641640
}
642641

643642
// 解码错误信息中的Unicode转义字符
@@ -653,7 +652,7 @@ func (c *EvaluatorSourceCodeServiceImpl) parseSyntaxValidationRetValJSON(retVal
653652
// processExecutionResult 处理执行结果,仅保留decodeUnicodeEscapes的处理
654653
func (c *EvaluatorSourceCodeServiceImpl) processExecutionResult(result *entity.ExecutionResult) (*entity.ExecutionResult, error) {
655654
if result == nil {
656-
return nil, fmt.Errorf("execution result is nil")
655+
return nil, errorx.NewByCode(errno.ExecutionResultNilCode, errorx.WithExtraMsg("execution result is nil"))
657656
}
658657

659658
// 处理输出信息
@@ -812,11 +811,11 @@ func (c *EvaluatorSourceCodeServiceImpl) parseEvaluationRetVal(retVal string) (s
812811
// 如果 JSON 解析失败,尝试 Python 字典格式
813812
jsonStr, convertErr := c.convertPythonDictToJSON(cleanedRetVal)
814813
if convertErr != nil {
815-
return nil, "", fmt.Errorf("failed to parse RetVal: %v, jsonStr: %s", err, jsonStr)
814+
return nil, "", errorx.NewByCode(errno.ExecutionResultParseFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to parse RetVal: %v, jsonStr: %s", err, jsonStr)))
816815
}
817816

818817
if err := json.Unmarshal([]byte(jsonStr), &result); err != nil {
819-
return nil, "", fmt.Errorf("failed to parse converted RetVal JSON: %v, jsonStr: %s", err, jsonStr)
818+
return nil, "", errorx.NewByCode(errno.ExecutionResultParseFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to parse converted RetVal JSON: %v, jsonStr: %s", err, jsonStr)))
820819
}
821820
}
822821

@@ -873,7 +872,7 @@ func (c *EvaluatorSourceCodeServiceImpl) parseEvaluationExecutionResult(result *
873872
func (c *EvaluatorSourceCodeServiceImpl) validatePythonCode(ctx context.Context, evaluator *entity.Evaluator, codeVersion *entity.CodeEvaluatorVersion) error {
874873
// 基础检查
875874
if codeVersion.CodeContent == "" {
876-
return fmt.Errorf("python code is empty")
875+
return errorx.NewByCode(errno.EmptyCodeContentCode, errorx.WithExtraMsg("python code is empty"))
877876
}
878877

879878
// 额外的Python特定安全检查
@@ -884,7 +883,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validatePythonCode(ctx context.Context,
884883
// 获取Runtime
885884
runtime, err := c.runtimeManager.GetRuntime(entity.LanguageTypePython)
886885
if err != nil {
887-
return fmt.Errorf("failed to get python runtime for validation: %v", err)
886+
return errorx.NewByCode(errno.RuntimeGetFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to get python runtime for validation: %v", err)))
888887
}
889888

890889
// 构建Python语法检查代码,参考pyodide客户端的AST验证方式
@@ -894,18 +893,18 @@ func (c *EvaluatorSourceCodeServiceImpl) validatePythonCode(ctx context.Context,
894893
ext := c.buildExtParams(evaluator)
895894
result, err := runtime.RunCode(ctx, syntaxCheckCode, "python", 10000, ext) // 10秒超时用于语法验证
896895
if err != nil {
897-
return fmt.Errorf("python syntax validation failed: %w", err)
896+
return errorx.NewByCode(errno.SyntaxValidationFailedCode, errorx.WithExtraMsg(fmt.Sprintf("python syntax validation failed: %v", err)))
898897
}
899898

900899
// 处理执行结果并解析stdout中的JSON
901900
valid, errorMsg, err := c.processSyntaxValidationExecutionResult(result)
902901
if err != nil {
903-
return fmt.Errorf("failed to process syntax validation result: %w", err)
902+
return errorx.NewByCode(errno.SyntaxValidationResultParseFailedCode, errorx.WithExtraMsg(err.Error()))
904903
}
905904
// 直接使用 processSyntaxValidationExecutionResult 的验证结果
906905
// 该方法已经完成了所有的 valid 字段解析和验证
907906
if !valid {
908-
return fmt.Errorf("python syntax error: %s", errorMsg)
907+
return errorx.NewByCode(errno.SyntaxValidationFailedCode, errorx.WithExtraMsg(fmt.Sprintf("python syntax error: %s", errorMsg)))
909908
}
910909

911910
return nil
@@ -915,7 +914,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validatePythonCode(ctx context.Context,
915914
func (c *EvaluatorSourceCodeServiceImpl) validateJavaScriptCode(ctx context.Context, evaluator *entity.Evaluator, codeVersion *entity.CodeEvaluatorVersion) error {
916915
// 基础检查
917916
if codeVersion.CodeContent == "" {
918-
return fmt.Errorf("javascript code is empty")
917+
return errorx.NewByCode(errno.EmptyCodeContentCode, errorx.WithExtraMsg("javascript code is empty"))
919918
}
920919

921920
// JavaScript特定安全检查
@@ -926,7 +925,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validateJavaScriptCode(ctx context.Cont
926925
// 获取Runtime
927926
runtime, err := c.runtimeManager.GetRuntime(entity.LanguageTypeJS)
928927
if err != nil {
929-
return fmt.Errorf("failed to get javascript runtime for validation: %v", err)
928+
return errorx.NewByCode(errno.RuntimeGetFailedCode, errorx.WithExtraMsg(fmt.Sprintf("failed to get javascript runtime for validation: %v", err)))
930929
}
931930

932931
// 构建JavaScript语法检查代码 (使用Builder模式)
@@ -936,19 +935,19 @@ func (c *EvaluatorSourceCodeServiceImpl) validateJavaScriptCode(ctx context.Cont
936935
ext := c.buildExtParams(evaluator)
937936
result, err := runtime.RunCode(ctx, syntaxCheckCode, "js", 10000, ext) // 与Python保持一致的10秒超时
938937
if err != nil {
939-
return fmt.Errorf("javascript syntax validation failed: %w", err)
938+
return errorx.NewByCode(errno.SyntaxValidationFailedCode, errorx.WithExtraMsg(fmt.Sprintf("javascript syntax validation failed: %v", err)))
940939
}
941940

942941
// 使用统一的结果处理方法 (与Python保持一致)
943942
valid, errorMsg, err := c.processSyntaxValidationExecutionResult(result)
944943
if err != nil {
945-
return fmt.Errorf("failed to process syntax validation result: %w", err)
944+
return errorx.NewByCode(errno.SyntaxValidationResultParseFailedCode, errorx.WithExtraMsg(err.Error()))
946945
}
947946

948947
// 直接使用 processSyntaxValidationExecutionResult 的验证结果
949948
// 该方法已经完成了所有的 valid 字段解析和验证
950949
if !valid {
951-
return fmt.Errorf("javascript syntax error: %s", errorMsg)
950+
return errorx.NewByCode(errno.SyntaxValidationFailedCode, errorx.WithExtraMsg(fmt.Sprintf("javascript syntax error: %s", errorMsg)))
952951
}
953952

954953
return nil
@@ -1055,7 +1054,7 @@ try {
10551054
// validateCodeSecurity 验证代码安全性
10561055
func (c *EvaluatorSourceCodeServiceImpl) validateCodeSecurity(codeVersion *entity.CodeEvaluatorVersion) error {
10571056
if strings.TrimSpace(codeVersion.CodeContent) == "" {
1058-
return fmt.Errorf("代码不能为空")
1057+
return errorx.NewByCode(errno.EmptyCodeContentCode, errorx.WithExtraMsg("代码不能为空"))
10591058
}
10601059

10611060
// 转换语言类型
@@ -1103,7 +1102,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validatePythonSpecificSecurity(code str
11031102

11041103
for _, pattern := range dangerousPatterns {
11051104
if matched, _ := regexp.MatchString(pattern, code); matched {
1106-
return fmt.Errorf("detected dangerous Python pattern")
1105+
return errorx.NewByCode(errno.DangerousImportDetectedCode, errorx.WithExtraMsg("detected dangerous Python pattern"))
11071106
}
11081107
}
11091108

@@ -1122,7 +1121,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validateJavaScriptSpecificSecurity(code
11221121

11231122
for _, pattern := range dangerousPatterns {
11241123
if matched, _ := regexp.MatchString(pattern, code); matched {
1125-
return fmt.Errorf("detected dangerous JavaScript pattern")
1124+
return errorx.NewByCode(errno.DangerousImportDetectedCode, errorx.WithExtraMsg("detected dangerous JavaScript pattern"))
11261125
}
11271126
}
11281127

@@ -1147,7 +1146,7 @@ func (c *EvaluatorSourceCodeServiceImpl) checkDangerousFunctions(code, language
11471146
// 创建正则表达式匹配函数调用
11481147
pattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(fn) + `\s*\(`)
11491148
if pattern.MatchString(code) {
1150-
return fmt.Errorf("安全违规: 检测到危险函数调用: %s", fn)
1149+
return errorx.NewByCode(errno.DangerousFunctionDetectedCode, errorx.WithExtraMsg(fmt.Sprintf("detected function: %s", fn)))
11511150
}
11521151
}
11531152

@@ -1187,9 +1186,9 @@ func (c *EvaluatorSourceCodeServiceImpl) checkDangerousImports(code, language st
11871186

11881187
for _, pattern := range patterns {
11891188
regex := regexp.MustCompile(pattern)
1190-
if regex.MatchString(code) {
1191-
return fmt.Errorf("安全违规: 检测到危险模块导入: %s", imp)
1192-
}
1189+
if regex.MatchString(code) {
1190+
return errorx.NewByCode(errno.DangerousImportDetectedCode, errorx.WithExtraMsg(fmt.Sprintf("detected import: %s", imp)))
1191+
}
11931192
}
11941193
}
11951194

@@ -1333,7 +1332,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validateExecEvaluationFunction(codeVers
13331332
case entity.LanguageTypeJS:
13341333
return c.validateJavaScriptExecEvaluationFunction(codeVersion.CodeContent)
13351334
default:
1336-
return fmt.Errorf("unsupported language type for exec_evaluation validation: %s", codeVersion.LanguageType)
1335+
return errorx.NewByCode(errno.UnsupportedLanguageTypeCode, errorx.WithExtraMsg(fmt.Sprintf("unsupported language type for exec_evaluation validation: %s", codeVersion.LanguageType)))
13371336
}
13381337
}
13391338

@@ -1344,7 +1343,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validatePythonExecEvaluationFunction(co
13441343
pattern := `(?m)^\s*def\s+exec_evaluation\s*\(`
13451344
regex := regexp.MustCompile(pattern)
13461345
if !regex.MatchString(code) {
1347-
return fmt.Errorf("代码中必须定义 exec_evaluation 函数。Python 函数定义格式:def exec_evaluation(turn_data):")
1346+
return errorx.NewByCode(errno.RequiredFunctionNotFoundCode, errorx.WithExtraMsg("代码中必须定义 exec_evaluation 函数。Python 函数定义格式:def exec_evaluation(turn_data):"))
13481347
}
13491348
return nil
13501349
}
@@ -1376,7 +1375,7 @@ func (c *EvaluatorSourceCodeServiceImpl) validateJavaScriptExecEvaluationFunctio
13761375
}
13771376
}
13781377

1379-
return fmt.Errorf("代码中必须定义 exec_evaluation 或 execEvaluation 函数。JavaScript 函数定义格式:function exec_evaluation(turn_data) { ... }")
1378+
return errorx.NewByCode(errno.RequiredFunctionNotFoundCode, errorx.WithExtraMsg("代码中必须定义 exec_evaluation 或 execEvaluation 函数。JavaScript 函数定义格式:function exec_evaluation(turn_data) { ... }"))
13801379
}
13811380

13821381
// ReportCodeRootSpanRequest Code评估器专用的上报请求结构

0 commit comments

Comments
 (0)