Skip to content

Go: Fix error code - #16807

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix533
Jul 10, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix533

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

As title.

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 10, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 10, 2026 06:46
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Handlers across admin, enterprise, chat, document, model, and system areas now use centralized common.Code* values instead of numeric error codes. A new CodeLackResources constant replaces literal code 1; success responses and payload shapes remain unchanged.

Changes

Error-code standardization

Layer / File(s) Summary
Shared error contract and focused handlers
internal/common/error_code.go, internal/handler/*.go
Adds CodeLackResources and standardizes error codes in chat, document, model, and system handlers.
Core admin handler responses
internal/admin/handler.go
Updates authentication, user management, administrator roles, and API-token endpoints to use semantic common error codes.
Admin service and operational responses
internal/admin/handler.go
Standardizes error handling for services, variables, sandbox operations, middleware, logging, and configuration endpoints.
Admin queue, ingestion, and model responses
internal/admin/handler.go
Standardizes validation and service failures for queue, ingestion, model, and engine endpoints.
Enterprise role and provider responses
internal/admin/enterprise_handler.go
Updates role, default-model, provider, instance, and license endpoints to use shared error codes.
Enterprise user-data responses
internal/admin/enterprise_handler.go
Standardizes validation, not-found, query, and server failures across reporting, quota, data, purge, and API-key endpoints.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested labels: ☯️ refactor

Poem

I’m a rabbit with codes in my tray,
Turning raw numbers semantic today.
Bad requests hop, server errors thump,
Missing resources no longer jump.
Clean handlers now quietly play.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says 'As title,' so it lacks the required summary and background context from the template. Replace it with a brief summary of the error-code handling changes and why they were needed.
Title check ❓ Inconclusive The title is related to the change, but it is too vague to clearly describe the actual error-code standardization work. Rename it to mention the concrete change, such as standardizing Go handler error codes and responses.
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 10, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 10, 2026 06:47
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 10, 2026 06:47
Signed-off-by: Jin Hai <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/admin/enterprise_handler.go (1)

248-250: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Missing return after bind error in SetRoleDefaultModel.

When c.ShouldBindJSON(&request) fails, the error response is written but execution continues to h.service.SetRoleDefaultModel with a zero-valued request. The sibling handler ResetRoleDefaultModel (line 274) correctly returns after the same error. This is a pre-existing bug, but it's adjacent to the error-code standardization changes in this PR.

🐛 Proposed fix
 	if err := c.ShouldBindJSON(&request); err != nil {
 		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
+		return
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/enterprise_handler.go` around lines 248 - 250, In
SetRoleDefaultModel, return immediately after c.ShouldBindJSON(&request) fails
and the bad-request response is written, matching ResetRoleDefaultModel, so the
service is not called with an invalid zero-valued request.
🧹 Nitpick comments (2)
internal/admin/handler.go (1)

756-756: 🎯 Functional Correctness | 🔵 Trivial | 🏗️ Heavy lift

Consider using CodeServerError for service-call failures currently mapped to CodeBadRequest.

Multiple service-layer failures (e.g., ListSandboxProviders, GetSandboxConfig, SetSandboxConfig, ListMessagesFromQueue, PublishMessageToQueue, RemoveIngestionTasks, StopIngestionTasks) return CodeBadRequest (400). These were 400 before this PR, so no regression occurred, but a server-side/service failure is semantically a CodeServerError (500). Since the PR's goal is to fix error codes, consider correcting these while you're here.

Also applies to: 773-773, 784-784, 817-817, 921-921, 960-960, 967-967, 989-989, 1033-1033, 1056-1056, 1064-1064, 1087-1087, 1102-1102

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` at line 756, Update the affected admin handlers,
including ListSandboxProviders, GetSandboxConfig, SetSandboxConfig,
ListMessagesFromQueue, PublishMessageToQueue, RemoveIngestionTasks, and
StopIngestionTasks, to map service-layer failures to common.CodeServerError
instead of common.CodeBadRequest while preserving client-validation errors as
CodeBadRequest.
internal/admin/enterprise_handler.go (1)

121-123: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

DropRole returns CodeNotFound for all service errors.

Any error from h.service.DropRole—including server errors—is mapped to CodeNotFound with message "Role not found". This masks genuine server failures as not-found responses. Consider checking for a specific not-found error (like errors.Is(err, common.ErrNotFound)) and falling back to CodeServerError for other errors, consistent with the pattern used in ListResources (lines 209-213).

♻️ Proposed refactor
 	role, err := h.service.DropRole(roleName)
 	if err != nil {
-		common.ErrorWithCode(c, common.CodeNotFound, "Role not found")
+		if errors.Is(err, common.ErrNotFound) {
+			common.ErrorWithCode(c, common.CodeNotFound, "Role not found")
+			return
+		}
+		common.ErrorWithCode(c, common.CodeServerError, err.Error())
 		return
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/enterprise_handler.go` around lines 121 - 123, Update the
error handling in the DropRole handler to distinguish not-found errors from
other service failures: use errors.Is(err, common.ErrNotFound) to return
CodeNotFound with “Role not found”, and map all other errors to CodeServerError,
following the pattern in ListResources.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 1390-1391: In the handlers ListUsersStorage, ListUsersDocuments,
ListUsersIndex, and ListUsersQuota, add an immediate return after
common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer") when
strconv.Atoi(topStr) fails, preventing fallthrough to the service call.

In `@internal/admin/handler.go`:
- Around line 1125-1128: ListIngestionTasks continues after sending an error
response, causing a second success response to be written. Add an immediate
return after common.ErrorWithCode in ListIngestionTasks, before
common.SuccessWithData.
- Around line 468-469: Change the error code in the DeleteUserAPIToken failure
branch of the relevant handler method from common.CodeBadRequest to
common.CodeServerError, matching the other service-call error paths in
internal/admin/handler.go.
- Around line 1237-1242: In ShowModel, standardize the empty encoded-name error
path to use common.ErrorWithCode(c, common.CodeBadRequest, ...) instead of
common.ResponseWithHttpCodeData, matching the subsequent validation errors.

In `@internal/common/error_code.go`:
- Line 25: Add a corresponding entry for CodeLackResources in the errorMessages
map, using a clear meaningful description consistent with the other error codes,
so CodeLackResources.Message() no longer returns "Unknown error".

In `@internal/handler/document.go`:
- Line 1479: In the task_ids validation branch of the document handler, replace
common.CodeLackResources with common.CodeBadRequest when reporting the
required-input error via common.ErrorWithCode, preserving the existing message
and response behavior.

---

Outside diff comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 248-250: In SetRoleDefaultModel, return immediately after
c.ShouldBindJSON(&request) fails and the bad-request response is written,
matching ResetRoleDefaultModel, so the service is not called with an invalid
zero-valued request.

---

Nitpick comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 121-123: Update the error handling in the DropRole handler to
distinguish not-found errors from other service failures: use errors.Is(err,
common.ErrNotFound) to return CodeNotFound with “Role not found”, and map all
other errors to CodeServerError, following the pattern in ListResources.

In `@internal/admin/handler.go`:
- Line 756: Update the affected admin handlers, including ListSandboxProviders,
GetSandboxConfig, SetSandboxConfig, ListMessagesFromQueue,
PublishMessageToQueue, RemoveIngestionTasks, and StopIngestionTasks, to map
service-layer failures to common.CodeServerError instead of
common.CodeBadRequest while preserving client-validation errors as
CodeBadRequest.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1a0cd046-0c2c-4c1d-89c0-50cf7d5df358

📥 Commits

Reviewing files that changed from the base of the PR and between 7db3982 and 23d0569.

📒 Files selected for processing (7)
  • internal/admin/enterprise_handler.go
  • internal/admin/handler.go
  • internal/common/error_code.go
  • internal/handler/chat_session.go
  • internal/handler/document.go
  • internal/handler/models.go
  • internal/handler/system.go

Comment on lines +1390 to 1391
common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Missing return after "Top must be an integer" error response in four handlers.

In ListUsersStorage, ListUsersDocuments, ListUsersIndex, and ListUsersQuota, when strconv.Atoi(topStr) fails, common.ErrorWithCode writes the error response but execution falls through to the service call with top = 0. This double-writes a response and calls the service with an invalid parameter. Add return after each error response.

🐛 Proposed fix for all four handlers
 // ListUsersStorage
 	if err != nil {
 		common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")
+		return
 	}

 // ListUsersDocuments
 	if err != nil {
 		common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")
+		return
 	}

 // ListUsersIndex
 	if err != nil {
 		common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")
+		return
 	}

 // ListUsersQuota
 	if err != nil {
 		common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer")
+		return
 	}

Also applies to: 1434-1435, 1478-1479, 1534-1535

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/enterprise_handler.go` around lines 1390 - 1391, In the
handlers ListUsersStorage, ListUsersDocuments, ListUsersIndex, and
ListUsersQuota, add an immediate return after common.ErrorWithCode(c,
common.CodeBadRequest, "Top must be an integer") when strconv.Atoi(topStr)
fails, preventing fallthrough to the service call.

Comment thread internal/admin/handler.go
Comment on lines 468 to +469
if err = h.service.DeleteUserAPIToken(username, key); err != nil {
common.ErrorWithCode(c, 400, err.Error())
common.ErrorWithCode(c, common.CodeBadRequest, err.Error())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

DeleteUserAPIToken service error regressed from 500 to 400.

All other service-call failures in this file use common.CodeServerError (e.g., lines 425, 447, 549, 566). This handler's service error was previously 500 and is now CodeBadRequest (400), which is inconsistent and semantically wrong for a server-side failure.

🐛 Proposed fix
 	if err = h.service.DeleteUserAPIToken(username, key); err != nil {
-		common.ErrorWithCode(c, common.CodeBadRequest, err.Error())
+		common.ErrorWithCode(c, common.CodeServerError, err.Error())
 		return
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err = h.service.DeleteUserAPIToken(username, key); err != nil {
common.ErrorWithCode(c, 400, err.Error())
common.ErrorWithCode(c, common.CodeBadRequest, err.Error())
if err = h.service.DeleteUserAPIToken(username, key); err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` around lines 468 - 469, Change the error code in
the DeleteUserAPIToken failure branch of the relevant handler method from
common.CodeBadRequest to common.CodeServerError, matching the other service-call
error paths in internal/admin/handler.go.

Comment thread internal/admin/handler.go
Comment on lines 1125 to 1128
if err != nil {
common.ErrorWithCode(c, 500, err.Error())
common.ErrorWithCode(c, common.CodeServerError, err.Error())
}
common.SuccessWithData(c, tasks, "Get all tasks")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing return after error response in ListIngestionTasks.

common.ErrorWithCode writes the error response, but execution continues to common.SuccessWithData on line 1128, corrupting the HTTP response with both error and success bodies. Add a return after the error call.

🐛 Proposed fix
 	if err != nil {
 		common.ErrorWithCode(c, common.CodeServerError, err.Error())
+		return
 	}
 	common.SuccessWithData(c, tasks, "Get all tasks")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err != nil {
common.ErrorWithCode(c, 500, err.Error())
common.ErrorWithCode(c, common.CodeServerError, err.Error())
}
common.SuccessWithData(c, tasks, "Get all tasks")
if err != nil {
common.ErrorWithCode(c, common.CodeServerError, err.Error())
return
}
common.SuccessWithData(c, tasks, "Get all tasks")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` around lines 1125 - 1128, ListIngestionTasks
continues after sending an error response, causing a second success response to
be written. Add an immediate return after common.ErrorWithCode in
ListIngestionTasks, before common.SuccessWithData.

Comment thread internal/admin/handler.go
Comment on lines +1237 to 1242
common.ErrorWithCode(c, common.CodeBadRequest, err.Error())
return
}
if decodedModelName == "" {
common.ErrorWithCode(c, 400, "Decoded model name is empty")
common.ErrorWithCode(c, common.CodeBadRequest, "Decoded model name is empty")
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

ShowModel first error path (line 1231) was not standardized.

Lines 1237-1242 now use common.ErrorWithCode(c, common.CodeBadRequest, ...), but the empty-encoded-name check at line 1231 still uses common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, ...). For consistency within the same function, standardize all error paths.

♻️ Proposed fix for line 1231
 	if encodedModelName == "" {
-		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Encoded model name is empty")
+		common.ErrorWithCode(c, common.CodeBadRequest, "Encoded model name is empty")
 		return
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
common.ErrorWithCode(c, common.CodeBadRequest, err.Error())
return
}
if decodedModelName == "" {
common.ErrorWithCode(c, 400, "Decoded model name is empty")
common.ErrorWithCode(c, common.CodeBadRequest, "Decoded model name is empty")
return
if encodedModelName == "" {
common.ErrorWithCode(c, common.CodeBadRequest, "Encoded model name is empty")
return
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/admin/handler.go` around lines 1237 - 1242, In ShowModel,
standardize the empty encoded-name error path to use common.ErrorWithCode(c,
common.CodeBadRequest, ...) instead of common.ResponseWithHttpCodeData, matching
the subsequent validation errors.


const (
CodeSuccess ErrorCode = 0
CodeLackResources ErrorCode = 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

CodeLackResources is missing from the errorMessages map.

The new constant CodeLackResources (line 25) has no corresponding entry in the errorMessages map (lines 54-81). Any call to CodeLackResources.Message() will return "Unknown error" instead of a meaningful description. Since this code is actively used in internal/handler/document.go:1479, add a map entry.

🐛 Proposed fix: add missing errorMessages entry
 var errorMessages = map[ErrorCode]string{
 	CodeSuccess:                "Success",
+	CodeLackResources:          "Lack of resources",
 	CodeNotEffective:           "Not effective",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/common/error_code.go` at line 25, Add a corresponding entry for
CodeLackResources in the errorMessages map, using a clear meaningful description
consistent with the other error codes, so CodeLackResources.Message() no longer
returns "Unknown error".


if req.Tasks == nil || len(req.Tasks) == 0 {
common.ErrorWithCode(c, 1, "task_ids is required")
common.ErrorWithCode(c, common.CodeLackResources, "task_ids is required")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

CodeLackResources is semantically mismatched for a validation error.

"task_ids is required" is a client input validation failure, better suited to common.CodeBadRequest. CodeLackResources implies resource exhaustion. This preserves the prior numeric value (1) so behavior is unchanged, but the PR's standardization goal makes this a good time to correct the semantic.

♻️ Suggested semantic correction
-	common.ErrorWithCode(c, common.CodeLackResources, "task_ids is required")
+	common.ErrorWithCode(c, common.CodeBadRequest, "task_ids is required")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
common.ErrorWithCode(c, common.CodeLackResources, "task_ids is required")
common.ErrorWithCode(c, common.CodeBadRequest, "task_ids is required")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/handler/document.go` at line 1479, In the task_ids validation branch
of the document handler, replace common.CodeLackResources with
common.CodeBadRequest when reporting the required-input error via
common.ErrorWithCode, preserving the existing message and response behavior.

@JinHai-CN
JinHai-CN merged commit 2a83ad6 into infiniflow:main Jul 10, 2026
7 of 10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant