Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Refactor: refine error messages - use %W (#18834)

Wang Qiba625dc52b34
diff --git a/internal/agent/workflowx/loop.go b/internal/agent/workflowx/loop.go
index 5bee91237a..2019584ce3 100644
--- a/internal/agent/workflowx/loop.go
+++ b/internal/agent/workflowx/loop.go
@@ -388,7 +388,7 @@ func loadLoopSnapshot[T any](ctx context.Context, defaultMode LoopStreamMode) (l
}
var st loopInterruptState
if err := json.Unmarshal(payload, &st); err != nil {
- return loopSnapshot{}, fmt.Errorf("%w: decode state: %v", ErrLoopResumeStateInvalid, err)
+ return loopSnapshot{}, fmt.Errorf("%w: decode state: %w", ErrLoopResumeStateInvalid, err)
}
if st.Iteration < 1 {
return loopSnapshot{}, fmt.Errorf("%w: bad iteration %d", ErrLoopResumeStateInvalid, st.Iteration)
@@ -440,7 +440,7 @@ func runLoopInvoke[T any](ctx context.Context, nodeKey string, sub compose.Runna
current = input
} else {
if err := json.Unmarshal(snap.current, &current); err != nil {
- return zero, fmt.Errorf("%w: decode current input: %v", ErrLoopResumeStateInvalid, err)
+ return zero, fmt.Errorf("%w: decode current input: %w", ErrLoopResumeStateInvalid, err)
}
}
@@ -498,7 +498,7 @@ func runLoopInvoke[T any](ctx context.Context, nodeKey string, sub compose.Runna
// shouldQuit fails the loop.
quit, qErr := shouldQuit(ctx, iteration, current, next)
if qErr != nil {
- return zero, fmt.Errorf("%w: iteration %d: %v", ErrLoopQuitConditionFailed, iteration, qErr)
+ return zero, fmt.Errorf("%w: iteration %d: %w", ErrLoopQuitConditionFailed, iteration, qErr)
}
if quit {
bridgeState.delete(subCheckID)
@@ -570,7 +570,7 @@ func runLoopStream[T any](
current = input
} else {
if err := json.Unmarshal(snap.current, &current); err != nil {
- return nil, fmt.Errorf("%w: decode current input: %v", ErrLoopResumeStateInvalid, err)
+ return nil, fmt.Errorf("%w: decode current input: %w", ErrLoopResumeStateInvalid, err)
}
}
@@ -597,7 +597,7 @@ func runLoopStream[T any](
// chunk cursor for "resume from the first un-emitted chunk".
replayed, derr := decodeReplayChunks[T](replayHistory)
if derr != nil {
- return nil, fmt.Errorf("%w: decode replay chunks: %v", ErrLoopResumeStateInvalid, derr)
+ return nil, fmt.Errorf("%w: decode replay chunks: %w", ErrLoopResumeStateInvalid, derr)
}
streamReaders = append(streamReaders, schema.StreamReaderFromArray(replayed))
prefilledReplay = true
@@ -704,7 +704,7 @@ func runLoopStream[T any](
quit, qErr := shouldQuit(ctx, iteration, current, next)
if qErr != nil {
- pipeErrCh <- fmt.Errorf("%w: iteration %d: %v", ErrLoopQuitConditionFailed, iteration, qErr)
+ pipeErrCh <- fmt.Errorf("%w: iteration %d: %w", ErrLoopQuitConditionFailed, iteration, qErr)
return
}
if quit {
diff --git a/internal/agent/workflowx/parallel.go b/internal/agent/workflowx/parallel.go
index 12d50a33e6..602015b877 100644
--- a/internal/agent/workflowx/parallel.go
+++ b/internal/agent/workflowx/parallel.go
@@ -264,7 +264,7 @@ func AddParallelNode[I, O any](
}
compiled, err := sub.Compile(ctx, compileOpts...)
if err != nil {
- return nil, fmt.Errorf("%w: %s: %v", ErrParallelCompileFailed, key, err)
+ return nil, fmt.Errorf("%w: %s: %w", ErrParallelCompileFailed, key, err)
}
lambda, err := compose.AnyLambda[[]I, []O, struct{}](
@@ -329,7 +329,7 @@ func runParallelInvoke[I, O any](
if isResume && prev != nil {
var restored []I
if rErr := json.Unmarshal(prev.OriginalInputsJSON, &restored); rErr != nil {
- return nil, fmt.Errorf("%w: decode original_inputs_json: %v", ErrParallelResumeStateInvalid, rErr)
+ return nil, fmt.Errorf("%w: decode original_inputs_json: %w", ErrParallelResumeStateInvalid, rErr)
}
effectiveItems = restored
}
@@ -515,7 +515,7 @@ func loadParallelSnapshot(ctx context.Context) (*ParallelInterruptState, bool, e
if raw, ok := ctx.Value(parallelResumeBackdoorKey{}).([]byte); ok && len(raw) > 0 {
var st ParallelInterruptState
if err := json.Unmarshal(raw, &st); err != nil {
- return nil, false, fmt.Errorf("%w: decode state: %v", ErrParallelResumeStateInvalid, err)
+ return nil, false, fmt.Errorf("%w: decode state: %w", ErrParallelResumeStateInvalid, err)
}
if st.TotalCount < 0 {
return nil, false, fmt.Errorf("%w: negative total_count", ErrParallelResumeStateInvalid)
@@ -531,7 +531,7 @@ func loadParallelSnapshot(ctx context.Context) (*ParallelInterruptState, bool, e
}
var st ParallelInterruptState
if err := json.Unmarshal(payload, &st); err != nil {
- return nil, false, fmt.Errorf("%w: decode state: %v", ErrParallelResumeStateInvalid, err)
+ return nil, false, fmt.Errorf("%w: decode state: %w", ErrParallelResumeStateInvalid, err)
}
if st.TotalCount < 0 {
return nil, false, fmt.Errorf("%w: negative total_count", ErrParallelResumeStateInvalid)
diff --git a/internal/cli/cli.go b/internal/cli/cli.go
index 73bc16ea6f..dca88f429b 100644
--- a/internal/cli/cli.go
+++ b/internal/cli/cli.go
@@ -192,7 +192,7 @@ func ParseArgs(args []string) (*CommandLineConfig, error) {
hostVal := args[i+1]
h, port, err := parseHostPort(hostVal)
if err != nil {
- return nil, fmt.Errorf("invalid host format: %v", err)
+ return nil, fmt.Errorf("invalid host format: %w", err)
}
defaultApiServerConfig.IP = h
defaultApiServerConfig.Port = port
@@ -243,14 +243,14 @@ func ParseArgs(args []string) (*CommandLineConfig, error) {
data, err := os.ReadFile(configFile)
if err == nil {
if err = yaml.Unmarshal(data, &config); err != nil {
- return nil, fmt.Errorf("failed to parse rf.yml: %v", err)
+ return nil, fmt.Errorf("failed to parse rf.yml: %w", err)
}
if config.Host != "" {
var h string
var port int
h, port, err = parseHostPort(config.Host)
if err != nil {
- return nil, fmt.Errorf("invalid host in config file: %v", err)
+ return nil, fmt.Errorf("invalid host in config file: %w", err)
}
if defaultApiServerConfig.IP == "" {
defaultApiServerConfig.IP = h
@@ -277,7 +277,7 @@ func ParseArgs(args []string) (*CommandLineConfig, error) {
} else {
if configFile == "rf.yml" && os.IsNotExist(err) {
} else {
- return nil, fmt.Errorf("failed to read %s: %v", configFile, err)
+ return nil, fmt.Errorf("failed to read %s: %w", configFile, err)
}
}
@@ -335,7 +335,7 @@ func ParseArgs(args []string) (*CommandLineConfig, error) {
hostVal := args[i+1]
h, port, err := parseHostPort(hostVal)
if err != nil {
- return nil, fmt.Errorf("invalid host format: %v", err)
+ return nil, fmt.Errorf("invalid host format: %w", err)
}
AdminConfig.AdminHost = h
AdminConfig.AdminPort = port
@@ -394,7 +394,7 @@ func LoadDefaultConfigFile() (*ConfigFile, error) {
var config ConfigFile
if err = yaml.Unmarshal(data, &config); err != nil {
- return nil, fmt.Errorf("failed to parse rf.yml: %v", err)
+ return nil, fmt.Errorf("failed to parse rf.yml: %w", err)
}
return &config, nil
@@ -404,12 +404,12 @@ func LoadDefaultConfigFile() (*ConfigFile, error) {
func LoadConfigFileFromPath(path string) (*ConfigFile, error) {
data, err := os.ReadFile(path)
if err != nil {
- return nil, fmt.Errorf("failed to read config file %s: %v", path, err)
+ return nil, fmt.Errorf("failed to read config file %s: %w", path, err)
}
var config ConfigFile
if err = yaml.Unmarshal(data, &config); err != nil {
- return nil, fmt.Errorf("failed to parse config file %s: %v", path, err)
+ return nil, fmt.Errorf("failed to parse config file %s: %w", path, err)
}
return &config, nil
diff --git a/internal/cli/filesystem/skill_install.go b/internal/cli/filesystem/skill_install.go
index bb319c9af4..dbc50d2c7f 100644
--- a/internal/cli/filesystem/skill_install.go
+++ b/internal/cli/filesystem/skill_install.go
@@ -258,7 +258,7 @@ func (c *SkillInstallCommand) uninstallSkill(ctx stdctx.Context, spaceID, skillN
// Return error if both failed
if indexErr != nil && folderErr != nil {
- return fmt.Errorf("failed to uninstall: index (%v), folder (%v)", indexErr, folderErr)
+ return fmt.Errorf("failed to uninstall: index (%w), folder (%w)", indexErr, folderErr)
}
return nil
diff --git a/internal/cli/filesystem/skill_uninstall.go b/internal/cli/filesystem/skill_uninstall.go
index ec2f7ea9cc..0b778180be 100644
--- a/internal/cli/filesystem/skill_uninstall.go
+++ b/internal/cli/filesystem/skill_uninstall.go
@@ -98,7 +98,7 @@ func (c *SkillUninstallCommand) uninstallSkill(ctx stdctx.Context, spaceID, skil
fmt.Println()
if indexErr != nil && folderErr != nil {
- return fmt.Errorf("failed to completely uninstall skill '%s': index deletion failed (%v), folder deletion failed (%v)",
+ return fmt.Errorf("failed to completely uninstall skill '%s': index deletion failed (%w), folder deletion failed (%w)",
skillName, indexErr, folderErr)
}
if indexErr != nil {
diff --git a/internal/engine/redis/redis.go b/internal/engine/redis/redis.go
index 0bf424e604..874c873e37 100644
--- a/internal/engine/redis/redis.go
+++ b/internal/engine/redis/redis.go
@@ -385,7 +385,7 @@ func (r *Client) GetOrCreateKey(ctx context.Context, key string, value string) (
// SETNX returns true if the key was set, false if it already existed
success, err := r.client.SetNX(ctx, key, value, 0).Result()
if err != nil {
- return "", fmt.Errorf("failed to set key in Redis: %v", err)
+ return "", fmt.Errorf("failed to set key in Redis: %w", err)
}
if success {
@@ -397,7 +397,7 @@ func (r *Client) GetOrCreateKey(ctx context.Context, key string, value string) (
// Retrieve and return that key
finalKey, err := r.client.Get(ctx, key).Result()
if err != nil {
- return "", fmt.Errorf("failed to get key set by another process: %v", err)
+ return "", fmt.Errorf("failed to get key set by another process: %w", err)
}
return finalKey, nil
diff --git a/internal/handler/agent_component.go b/internal/handler/agent_component.go
index b79973204c..54ec0f56ed 100644
--- a/internal/handler/agent_component.go
+++ b/internal/handler/agent_component.go
@@ -97,7 +97,7 @@ func (h *AgentHandler) componentInputForm(ctx context.Context, dslMap map[string
params, _ := dsl.ExtractComponentParams(dslMap, componentID)
comp, err := runtime.DefaultFactory()(name, params)
if err != nil {
- return nil, fmt.Errorf("%w: component factory: %v", dsl.ErrMalformedDSL, err)
+ return nil, fmt.Errorf("%w: component factory: %w", dsl.ErrMalformedDSL, err)
}
getter, ok := comp.(interface{ GetInputForm() map[string]any })
if !ok {
diff --git a/internal/handler/agent_webhook_schema.go b/internal/handler/agent_webhook_schema.go
index 6f3647fe09..09b647a6cb 100644
--- a/internal/handler/agent_webhook_schema.go
+++ b/internal/handler/agent_webhook_schema.go
@@ -229,7 +229,7 @@ func extractBySchema(data map[string]any, schema map[string]any, name string) (m
// 3. Auto cast (only matters for string→typed; pass-through otherwise).
casted, err := autoCastValue(raw, fieldType)
if err != nil {
- return nil, fmt.Errorf("%s.%s auto-cast failed: %s", name, field, err.Error())
+ return nil, fmt.Errorf("%s.%s auto-cast failed: %w", name, field, err)
}
// 4. Type validation.
diff --git a/internal/handler/agent_webhook_security.go b/internal/handler/agent_webhook_security.go
index 80a5124249..fbb4fada1d 100644
--- a/internal/handler/agent_webhook_security.go
+++ b/internal/handler/agent_webhook_security.go
@@ -294,7 +294,7 @@ func validateRateLimit(ctx context.Context, canvasID string, cfg map[string]any)
zap.String("canvas_id", canvasID), zap.Error(err))
return nil
}
- return fmt.Errorf("rate limit error: %s", err.Error())
+ return fmt.Errorf("rate limit error: %w", err)
}
if !allowed {
return fmt.Errorf("too many requests (rate limit exceeded)")
@@ -463,7 +463,7 @@ func validateJWTAuth(c *gin.Context, cfg map[string]any) error {
token, err := jwt.Parse(tokenStr, keyFunc, parserOpts...)
if err != nil {
- return fmt.Errorf("invalid jwt: %s", err.Error())
+ return fmt.Errorf("invalid jwt: %w", err)
}
if !token.Valid {
return fmt.Errorf("invalid jwt")
@@ -499,13 +499,13 @@ func jwtKeyFunc(alg, secret string) (jwt.Keyfunc, error) {
case "RS256", "RS384", "RS512":
pub, err := jwt.ParseRSAPublicKeyFromPEM([]byte(secret))
if err != nil {
- return nil, fmt.Errorf("jwt rsa public key: %s", err.Error())
+ return nil, fmt.Errorf("jwt rsa public key: %w", err)
}
return func(_ *jwt.Token) (any, error) { return pub, nil }, nil
case "ES256", "ES384", "ES512":
pub, err := jwt.ParseECPublicKeyFromPEM([]byte(secret))
if err != nil {
- return nil, fmt.Errorf("jwt ec public key: %s", err.Error())
+ return nil, fmt.Errorf("jwt ec public key: %w", err)
}
return func(_ *jwt.Token) (any, error) { return pub, nil }, nil
}
diff --git a/internal/harness/core/agent_loop_agent.go b/internal/harness/core/agent_loop_agent.go
index 4e856397d9..51d6cf5fc2 100644
--- a/internal/harness/core/agent_loop_agent.go
+++ b/internal/harness/core/agent_loop_agent.go
@@ -210,7 +210,7 @@ func (l *AgentLoop[T]) runAgentAndHandleEvents(
}
if err := finalizeCheckpoint(); err != nil {
if handleErr != nil {
- handleErr = fmt.Errorf("%w; checkpoint error: %v", handleErr, err)
+ handleErr = fmt.Errorf("%w; checkpoint error: %w", handleErr, err)
} else {
handleErr = err
}
@@ -225,7 +225,7 @@ func (l *AgentLoop[T]) runAgentAndHandleEvents(
<-done
if err := finalizeCheckpoint(); err != nil {
if handleErr != nil {
- handleErr = fmt.Errorf("%w; checkpoint error: %v", handleErr, err)
+ handleErr = fmt.Errorf("%w; checkpoint error: %w", handleErr, err)
} else {
handleErr = err
}
diff --git a/internal/harness/core/multi_turn_integration_test.go b/internal/harness/core/multi_turn_integration_test.go
index 8e6e4d10b9..53aa890b3a 100644
--- a/internal/harness/core/multi_turn_integration_test.go
+++ b/internal/harness/core/multi_turn_integration_test.go
@@ -605,7 +605,7 @@ func TestMultiTurn_ConcurrentSameRunner(t *testing.T) {
break
}
if ev.Err != nil {
- errCh <- fmt.Errorf("run %d err: %v", id, ev.Err)
+ errCh <- fmt.Errorf("run %d err: %w", id, ev.Err)
}
}
}(i)
diff --git a/internal/harness/core/react_retry_test.go b/internal/harness/core/react_retry_test.go
index 0bf39c4338..9a6fbd6193 100644
--- a/internal/harness/core/react_retry_test.go
+++ b/internal/harness/core/react_retry_test.go
@@ -3,6 +3,7 @@ package core
import (
"context"
"errors"
+ "fmt"
"io"
"sync/atomic"
"testing"
@@ -284,7 +285,7 @@ func TestRetry_ShouldRetry_Generate_RewriteError(t *testing.T) {
if rc.Err != nil {
return &RetryDecision{
Retry: false,
- RewriteError: errors.New("rewritten: " + rc.Err.Error()),
+ RewriteError: fmt.Errorf("rewritten: %w", rc.Err),
}
}
return &RetryDecision{Retry: false}
diff --git a/internal/harness/graph/graph/graph_concurrency_test.go b/internal/harness/graph/graph/graph_concurrency_test.go
index 1384636508..50ed3782c3 100644
--- a/internal/harness/graph/graph/graph_concurrency_test.go
+++ b/internal/harness/graph/graph/graph_concurrency_test.go
@@ -420,7 +420,7 @@ func TestGraph_ConcurrentInvoke_InterruptRace(t *testing.T) {
_, err := cg.Invoke(t.Context(), map[string]interface{}{"val": ""})
// Interrupt is expected — not a failure
if err != nil {
- errs <- fmt.Errorf("interrupt (expected): %v", err)
+ errs <- fmt.Errorf("interrupt (expected): %w", err)
}
})
}
@@ -628,7 +628,7 @@ func TestGraph_ConcurrentInvoke_TimeoutRace(t *testing.T) {
defer cancel()
_, err := cg.Invoke(ctx, map[string]interface{}{"val": ""})
if err != nil {
- errs <- fmt.Errorf("goroutine %d: %v", id, err)
+ errs <- fmt.Errorf("goroutine %d: %w", id, err)
}
}(i)
}
diff --git a/internal/harness/graph/graph/loop.go b/internal/harness/graph/graph/loop.go
index 86badf13c7..6e983721dc 100644
--- a/internal/harness/graph/graph/loop.go
+++ b/internal/harness/graph/graph/loop.go
@@ -159,7 +159,7 @@ func runLoop(
if snap.CurrentInput != nil {
var decoded interface{}
if err := json.Unmarshal(snap.CurrentInput, &decoded); err != nil {
- return nil, fmt.Errorf("%w: decode current input: %v", ErrLoopResumeStateInvalid, err)
+ return nil, fmt.Errorf("%w: decode current input: %w", ErrLoopResumeStateInvalid, err)
}
current = decoded
} else {
diff --git a/internal/harness/graph/graph/parallel.go b/internal/harness/graph/graph/parallel.go
index 4146362fac..b875fea3b0 100644
--- a/internal/harness/graph/graph/parallel.go
+++ b/internal/harness/graph/graph/parallel.go
@@ -183,7 +183,7 @@ func runParallel(
continue
}
if normalErr == nil {
- normalErr = fmt.Errorf("%w: item %d: %v", ErrParallelItemFailed, r.index, r.err)
+ normalErr = fmt.Errorf("%w: item %d: %w", ErrParallelItemFailed, r.index, r.err)
}
}
diff --git a/internal/service/deep_researcher.go b/internal/service/deep_researcher.go
index 142b936b9a..1c2611a027 100644
--- a/internal/service/deep_researcher.go
+++ b/internal/service/deep_researcher.go
@@ -585,11 +585,12 @@ func (dr *DeepResearcher) genJSON(
result interface{},
) error {
maxRetry := 2
- var lastAns, lastErr string
+ var lastAns string
+ var lastErr error
for attempt := 0; attempt < maxRetry; attempt++ {
userPrompt := "Output:\n"
- if attempt > 0 && lastAns != "" && lastErr != "" {
+ if attempt > 0 && lastAns != "" && lastErr != nil {
// Append correction to user message on retry
userPrompt += fmt.Sprintf(
"\nGenerated JSON is as following:\n%s\nBut exception while loading:\n%s\nPlease reconsider and correct it.",
@@ -610,14 +611,14 @@ func (dr *DeepResearcher) genJSON(
repaired = resp
}
if err := json.Unmarshal([]byte(repaired), result); err != nil {
- lastErr = err.Error()
+ lastErr = err
common.Warn("genJSON: JSON parse failed, retrying",
zap.Error(err), zap.Int("attempt", attempt))
continue
}
return nil
}
- return fmt.Errorf("genJSON: failed after %d attempts: %s", maxRetry, lastErr)
+ return fmt.Errorf("genJSON: failed after %d attempts: %w", maxRetry, lastErr)
}
// sufficiencyCheck asks the LLM whether retrieved content is sufficient.
diff --git a/internal/service/document/document_ingest.go b/internal/service/document/document_ingest.go
index 6ddd5cfe04..acbdc24a35 100644
--- a/internal/service/document/document_ingest.go
+++ b/internal/service/document/document_ingest.go
@@ -37,7 +37,7 @@ func (s *DocumentService) Ingest(ctx context.Context, userID string, req *Ingest
docs, err := s.documentDAO.GetByIDs(ctx, dao.DB, req.DocIDs)
if err != nil {
- return common.CodeExceptionError, fmt.Errorf("fail to get documents: %s", err.Error())
+ return common.CodeExceptionError, fmt.Errorf("fail to get documents: %w", err)
}
docsByID := make(map[string]*entity.Document, len(docs))
diff --git a/internal/service/document/document_parse.go b/internal/service/document/document_parse.go
index 9ba0823d06..4c42b1d27b 100644
--- a/internal/service/document/document_parse.go
+++ b/internal/service/document/document_parse.go
@@ -351,7 +351,7 @@ var errParseNotRunning = errors.New("parse task is not in running status")
func (s *DocumentService) CancelDocParse(ctx context.Context, doc *entity.Document) error {
task, err := s.ingestionTaskDAO.GetByDocumentID(ctx, dao.DB, doc.ID)
if err != nil {
- return fmt.Errorf("failed to get ingestion task for %s: %v", doc.ID, err)
+ return fmt.Errorf("failed to get ingestion task for %s: %w", doc.ID, err)
}
docRun := ""
@@ -365,12 +365,12 @@ func (s *DocumentService) CancelDocParse(ctx context.Context, doc *entity.Docume
if task != nil {
if _, err = s.ingestionTaskSvc.RequestStop(ctx, task.ID); err != nil {
- return fmt.Errorf("failed to stop ingestion task %s: %v", task.ID, err)
+ return fmt.Errorf("failed to stop ingestion task %s: %w", task.ID, err)
}
}
if upErr := s.documentDAO.UpdateByID(ctx, dao.DB, doc.ID, map[string]interface{}{"run": string(entity.TaskStatusCancel)}); upErr != nil {
- return fmt.Errorf("failed to update document %s: %v", doc.ID, upErr)
+ return fmt.Errorf("failed to update document %s: %w", doc.ID, upErr)
}
return nil
}
diff --git a/internal/service/ingestion_task_service.go b/internal/service/ingestion_task_service.go
index 60a8ff321b..036791133a 100644
--- a/internal/service/ingestion_task_service.go
+++ b/internal/service/ingestion_task_service.go
@@ -403,7 +403,7 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit
clearCancelFlag(ctx, existing.ID)
if err = s.enqueueTask(existing.ID); err != nil {
if rollbackErr := s.rollbackRetriedTask(ctx, existing.ID, originalStatus); rollbackErr != nil {
- return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %v)", existing.ID, err, rollbackErr)
+ return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %w)", existing.ID, err, rollbackErr)
}
return nil, err
}
@@ -418,7 +418,7 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit
}
if err = s.enqueueTask(created.ID); err != nil {
if rollbackErr := s.rollbackCreatedTask(ctx, created.ID); rollbackErr != nil {
- return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %v)", created.ID, err, rollbackErr)
+ return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %w)", created.ID, err, rollbackErr)
}
return nil, err
}
diff --git a/internal/service/mcp.go b/internal/service/mcp.go
index 4e16734628..b2d2c28c33 100644
--- a/internal/service/mcp.go
+++ b/internal/service/mcp.go
@@ -717,7 +717,7 @@ func (s *MCPService) TestServer(ctx context.Context, mcpID string, req *TestServ
// generic FetchTools error and re-classified by the handler as a 500.
// FetchTools repeats the check internally; the second call is cheap.
if _, _, err := utility.AssertURLSafe(req.URL); err != nil {
- return nil, fmt.Errorf("%w: %s", ErrMCPInvalidURL, err.Error())
+ return nil, fmt.Errorf("%w: %w", ErrMCPInvalidURL, err)
}
timeoutSec := req.Timeout
@@ -749,7 +749,7 @@ func (s *MCPService) TestServer(ctx context.Context, mcpID string, req *TestServ
Timeout: timeout,
})
if err != nil {
- return nil, fmt.Errorf("%w: Test MCP error (id=%s): %v", ErrMCPTestFailed, mcpID, err)
+ return nil, fmt.Errorf("%w: Test MCP error (id=%s): %w", ErrMCPTestFailed, mcpID, err)
}
out := make([]map[string]interface{}, 0, len(tools))
diff --git a/internal/service/memory_extractor.go b/internal/service/memory_extractor.go
index 73ac4fa3cc..4ece2332f4 100644
--- a/internal/service/memory_extractor.go
+++ b/internal/service/memory_extractor.go
@@ -119,7 +119,7 @@ func (s *MemoryMessageService) HandleSaveToMemoryTask(ctx context.Context, paylo
if err = s.saveExtractedToMemory(ctx, memoryID, msg, sourceID, taskID); err != nil {
s.updateTaskProgress(ctx, taskID, -1, err.Error())
- return fmt.Errorf("%w: %v", ErrMemoryTaskTerminal, err)
+ return fmt.Errorf("%w: %w", ErrMemoryTaskTerminal, err)
}
return nil
}
diff --git a/internal/service/model_service.go b/internal/service/model_service.go
index ed25e36366..1b15f6f098 100644
--- a/internal/service/model_service.go
+++ b/internal/service/model_service.go
@@ -199,7 +199,7 @@ func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerNam
}
err = m.modelProviderDAO.Create(ctx, dao.DB, tenantModelProvider)
if err != nil {
- return common.CodeServerError, fmt.Errorf("fail to create model provider: %s", err.Error())
+ return common.CodeServerError, fmt.Errorf("fail to create model provider: %w", err)
}
return common.CodeSuccess, nil
}
@@ -647,7 +647,7 @@ func (m *ModelProviderService) CreateProviderInstance(ctx context.Context, provi
}
err = m.modelInstanceDAO.Create(ctx, dao.DB, tenantModelInstance)
if err != nil {
- return common.CodeServerError, fmt.Errorf("fail to create model instance: %s", err.Error())
+ return common.CodeServerError, fmt.Errorf("fail to create model instance: %w", err)
}
// Add models to the instance.
@@ -730,7 +730,7 @@ func (m *ModelProviderService) CreateNameOnlyProviderInstance(ctx context.Contex
}
err = m.modelInstanceDAO.Create(ctx, dao.DB, tenantModelInstance)
if err != nil {
- return common.CodeServerError, fmt.Errorf("fail to create model instance: %s", err.Error())
+ return common.CodeServerError, fmt.Errorf("fail to create model instance: %w", err)
}
return common.CodeSuccess, nil
@@ -774,7 +774,7 @@ func (m *ModelProviderService) addModelToInstance(ctx context.Context, tenantID,
}
extraBytes, err := json.Marshal(extraFields)
if err != nil {
- return fmt.Errorf("fail to marshal extra: %s", err.Error())
+ return fmt.Errorf("fail to marshal extra: %w", err)
}
modelID := utility.GenerateToken()
@@ -789,7 +789,7 @@ func (m *ModelProviderService) addModelToInstance(ctx context.Context, tenantID,
}
if err = m.modelDAO.Create(ctx, dao.DB, tenantModel); err != nil {
- return fmt.Errorf("fail to create model '%s': %s", model.ModelName, err.Error())
+ return fmt.Errorf("fail to create model '%s': %w", model.ModelName, err)
}
return nil
@@ -2051,7 +2051,7 @@ func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID
}
instanceUpdates["extra"] = string(extraBytes)
if err = m.modelInstanceDAO.UpdateByID(ctx, dao.DB, instance.ID, instanceUpdates); err != nil {
- return common.CodeServerError, fmt.Errorf("fail to update instance: %s", err.Error())
+ return common.CodeServerError, fmt.Errorf("fail to update instance: %w", err)
}
// Use the (possibly updated) instance_name for model operations.
@@ -3898,7 +3898,7 @@ func (m *ModelProviderService) AddModel(ctx context.Context, request *AddModelRe
}
if err = m.modelDAO.Create(ctx, dao.DB, tenantModel); err != nil {
- return common.CodeServerError, fmt.Errorf("fail to create model '%s': %s", modelName, err.Error())
+ return common.CodeServerError, fmt.Errorf("fail to create model '%s': %w", modelName, err)
}
return common.CodeSuccess, nil
diff --git a/internal/service/skill_indexer.go b/internal/service/skill_indexer.go
index 863287a980..42eb02baa5 100644
--- a/internal/service/skill_indexer.go
+++ b/internal/service/skill_indexer.go
@@ -19,6 +19,7 @@ package service
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"path/filepath"
"ragflow/internal/common"
@@ -280,7 +281,7 @@ func (s *SkillIndexerService) BatchIndexSkills(ctx context.Context, tenantID, sp
timestamp := now.UnixMilli()
isES := isElasticsearch(docEngine)
- var indexErrors []string
+ var indexErrors []error
for i, skill := range skills {
// Delete old versions (both new format and old format with version suffix)
// This ensures only the latest version is indexed
@@ -345,13 +346,13 @@ func (s *SkillIndexerService) BatchIndexSkills(ctx context.Context, tenantID, sp
common.Info("Batch: Calling IndexDocument", zap.String("indexName", indexName), zap.String("docID", docID), zap.Int("index", i))
if err := docEngine.IndexDocument(ctx, indexName, docID, doc); err != nil {
common.Error(fmt.Sprintf("Failed to index skill %s", skill.ID), err)
- indexErrors = append(indexErrors, fmt.Sprintf("%s: %v", skill.ID, err))
+ indexErrors = append(indexErrors, fmt.Errorf("%s: %w", skill.ID, err))
continue
}
}
if len(indexErrors) > 0 {
- return fmt.Errorf("failed to index %d skill(s): %s", len(indexErrors), strings.Join(indexErrors, "; "))
+ return fmt.Errorf("failed to index %d skill(s): %w", len(indexErrors), errors.Join(indexErrors...))
}
return nil
diff --git a/internal/service/toc_enhancer.go b/internal/service/toc_enhancer.go
index dfc5767b02..641d976c4c 100644
--- a/internal/service/toc_enhancer.go
+++ b/internal/service/toc_enhancer.go
@@ -461,10 +461,11 @@ func (e *TOCEnhancer) scoreEntries(ctx context.Context, entries []tocEntry, limi
var scores []tocRelevanceScore
maxRetry := 2
- var lastAns, lastErr string
+ var lastAns string
+ var lastErr error
for attempt := 0; attempt < maxRetry; attempt++ {
currentUser := userPrompt
- if attempt > 0 && lastAns != "" && lastErr != "" {
+ if attempt > 0 && lastAns != "" && lastErr != nil {
currentUser += fmt.Sprintf(
"\nGenerated JSON is as following:\n%s\nBut exception while loading:\n%s\nPlease reconsider and correct it.",
lastAns, lastErr,
@@ -496,15 +497,15 @@ func (e *TOCEnhancer) scoreEntries(ctx context.Context, entries []tocEntry, limi
repaired = raw
}
if err = json.Unmarshal([]byte(repaired), &scores); err != nil {
- lastErr = err.Error()
+ lastErr = err
common.Warn("TOC enhancer: JSON parse failed, retrying",
zap.Error(err), zap.Int("attempt", attempt))
continue
}
break
}
- if len(scores) == 0 && lastErr != "" {
- return nil, fmt.Errorf("toc scoring: parse failed after retries: %s", lastErr)
+ if len(scores) == 0 && lastErr != nil {
+ return nil, fmt.Errorf("toc scoring: parse failed after retries: %w", lastErr)
}
id2score := make(map[string][]float64)
diff --git a/internal/storage/gcs.go b/internal/storage/gcs.go
index fafd1c66ca..191c7906df 100644
--- a/internal/storage/gcs.go
+++ b/internal/storage/gcs.go
@@ -111,7 +111,7 @@ func (m *GCSStorage) Remove(ctx context.Context, bucketName, objectName string,
obj := m.client.Bucket(bucketName).Object(objectName)
if err := obj.Delete(ctx); err != nil {
- return fmt.Errorf("fail to delete object: %v", err)
+ return fmt.Errorf("fail to delete object: %w", err)
}
return nil
diff --git a/internal/syncer/connector/moodle.go b/internal/syncer/connector/moodle.go
index 0deafe3038..1770427e65 100644
--- a/internal/syncer/connector/moodle.go
+++ b/internal/syncer/connector/moodle.go
@@ -935,7 +935,7 @@ func moodleAssertURLSafe(ctx context.Context, rawURL, originURL string) (string,
}
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)
if err != nil {
- return "", nil, fmt.Errorf("Could not resolve hostname %q: %v", hostname, err)
+ return "", nil, fmt.Errorf("Could not resolve hostname %q: %w", hostname, err)
}
if len(addrs) == 0 {
return "", nil, fmt.Errorf("Hostname %q resolved to no addresses.", hostname)
diff --git a/internal/syncer/connector/rest_api.go b/internal/syncer/connector/rest_api.go
index c62b234645..2f33a42cfc 100644
--- a/internal/syncer/connector/rest_api.go
+++ b/internal/syncer/connector/rest_api.go
@@ -983,7 +983,7 @@ func assertRestAPIURLSafe(ctx context.Context, rawURL string) (string, net.IP, e
if restAPISSRFAllowLoopback {
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)
if err != nil {
- return "", nil, fmt.Errorf("Could not resolve hostname %q: %v", hostname, err)
+ return "", nil, fmt.Errorf("Could not resolve hostname %q: %w", hostname, err)
}
if len(addrs) == 0 {
return "", nil, fmt.Errorf("Hostname %q resolved to no addresses.", hostname)
@@ -993,7 +993,7 @@ func assertRestAPIURLSafe(ctx context.Context, rawURL string) (string, net.IP, e
addrs, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)
if err != nil {
- return "", nil, fmt.Errorf("Could not resolve hostname %q: %v", hostname, err)
+ return "", nil, fmt.Errorf("Could not resolve hostname %q: %w", hostname, err)
}
var first net.IP
for _, addr := range addrs {
diff --git a/internal/syncer/connector/salesforce.go b/internal/syncer/connector/salesforce.go
index daa8348e37..91d3b2ecf7 100644
--- a/internal/syncer/connector/salesforce.go
+++ b/internal/syncer/connector/salesforce.go
@@ -451,7 +451,7 @@ func (c *SalesforceConnector) apiURL(snap salesforceToken, path string) (string,
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
parsed, err := url.Parse(path)
if err != nil {
- return "", fmt.Errorf("Salesforce pagination URL is invalid: %v", err)
+ return "", fmt.Errorf("Salesforce pagination URL is invalid: %w", err)
}
if !strings.EqualFold(parsed.Scheme, "https") || !salesforceHostAllowed(parsed.Hostname()) {
return "", fmt.Errorf("Salesforce pagination URL must use HTTPS on an approved Salesforce host")
diff --git a/internal/syncer/connector/slack.go b/internal/syncer/connector/slack.go
index f0f8157b86..8effb14004 100644
--- a/internal/syncer/connector/slack.go
+++ b/internal/syncer/connector/slack.go
@@ -601,7 +601,7 @@ func (c *SlackConnector) joinChannel(ctx context.Context, channel slackChannel)
var apiErr *slackAPIError
if errors.As(err, &apiErr) {
if _, ok := slackUnjoinableErrors[apiErr.code]; ok {
- return fmt.Errorf("%w: %v", errSlackChannelUnavailable, err)
+ return fmt.Errorf("%w: %w", errSlackChannelUnavailable, err)
}
}
return err
diff --git a/internal/syncer/connector/webdav.go b/internal/syncer/connector/webdav.go
index 91a43a1a18..ba8de70240 100644
--- a/internal/syncer/connector/webdav.go
+++ b/internal/syncer/connector/webdav.go
@@ -131,7 +131,7 @@ func (c *WebDAVConnector) Validate(ctx context.Context) error {
return fmt.Errorf("remote path '%s' does not exist on WebDAV server", c.remotePath)
}
}
- return fmt.Errorf("WebDAV validation failed for path '%s': %v", testPath, err)
+ return fmt.Errorf("WebDAV validation failed for path '%s': %w", testPath, err)
}
// ValidateConnectorSetting validates WebDAV settings from an unsaved config.
diff --git a/internal/utility/mcp_client.go b/internal/utility/mcp_client.go
index 1b484a3a20..eb9429c17a 100644
--- a/internal/utility/mcp_client.go
+++ b/internal/utility/mcp_client.go
@@ -751,7 +751,7 @@ func formatMCPError(method string, e *jsonRPCError) error {
// when a low-level connection fails (authentication / network).
func mapMCPConnectionError(err error) error {
if errors.Is(err, context.DeadlineExceeded) {
- return errors.New("timeout connecting to MCP server")
+ return fmt.Errorf("timeout connecting to MCP server: %w", err)
}
- return fmt.Errorf("connection failed (possibly due to auth error). Please check authentication settings first: %v", err)
+ return fmt.Errorf("connection failed (possibly due to auth error). Please check authentication settings first: %w", err)
}
diff --git a/internal/utility/ssrf.go b/internal/utility/ssrf.go
index 60cc256444..8c7b499a79 100644
--- a/internal/utility/ssrf.go
+++ b/internal/utility/ssrf.go
@@ -84,7 +84,7 @@ var AssertURLSafe = func(rawURL string) (hostname, resolvedIP string, err error)
allowAny := allowAnyHost()
addresses, err := LookupHost(hostname)
if err != nil {
- return "", "", fmt.Errorf("could not resolve hostname '%s': %v", hostname, err)
+ return "", "", fmt.Errorf("could not resolve hostname '%s': %w", hostname, err)
}
if len(addresses) == 0 {
return "", "", fmt.Errorf("hostname '%s' resolved to no addresses", hostname)
diff --git a/internal/utility/token.go b/internal/utility/token.go
index 171e72aebb..ea13984ea2 100644
--- a/internal/utility/token.go
+++ b/internal/utility/token.go
@@ -196,7 +196,7 @@ func bytesToInt(data []byte) int64 {
func GenerateSecretKey() (string, error) {
bytes := make([]byte, 32) // 32 bytes = 256 bits
if _, err := rand.Read(bytes); err != nil {
- return "", fmt.Errorf("failed to generate random key: %v", err)
+ return "", fmt.Errorf("failed to generate random key: %w", err)
}
return hex.EncodeToString(bytes), nil
}