Repository navigation
Go: Fix error code - #16807
Go: Fix error code#16807
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughHandlers across admin, enterprise, chat, document, model, and system areas now use centralized ChangesError-code standardization
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
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. Comment |
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winMissing
returnafter bind error inSetRoleDefaultModel.When
c.ShouldBindJSON(&request)fails, the error response is written but execution continues toh.service.SetRoleDefaultModelwith a zero-valued request. The sibling handlerResetRoleDefaultModel(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 liftConsider using
CodeServerErrorfor service-call failures currently mapped toCodeBadRequest.Multiple service-layer failures (e.g.,
ListSandboxProviders,GetSandboxConfig,SetSandboxConfig,ListMessagesFromQueue,PublishMessageToQueue,RemoveIngestionTasks,StopIngestionTasks) returnCodeBadRequest(400). These were400before this PR, so no regression occurred, but a server-side/service failure is semantically aCodeServerError(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
DropRolereturnsCodeNotFoundfor all service errors.Any error from
h.service.DropRole—including server errors—is mapped toCodeNotFoundwith message "Role not found". This masks genuine server failures as not-found responses. Consider checking for a specific not-found error (likeerrors.Is(err, common.ErrNotFound)) and falling back toCodeServerErrorfor other errors, consistent with the pattern used inListResources(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
📒 Files selected for processing (7)
internal/admin/enterprise_handler.gointernal/admin/handler.gointernal/common/error_code.gointernal/handler/chat_session.gointernal/handler/document.gointernal/handler/models.gointernal/handler/system.go
| common.ErrorWithCode(c, common.CodeBadRequest, "Top must be an integer") | ||
| } |
There was a problem hiding this comment.
🩺 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.
| if err = h.service.DeleteUserAPIToken(username, key); err != nil { | ||
| common.ErrorWithCode(c, 400, err.Error()) | ||
| common.ErrorWithCode(c, common.CodeBadRequest, err.Error()) |
There was a problem hiding this comment.
🎯 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.
| 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.
| if err != nil { | ||
| common.ErrorWithCode(c, 500, err.Error()) | ||
| common.ErrorWithCode(c, common.CodeServerError, err.Error()) | ||
| } | ||
| common.SuccessWithData(c, tasks, "Get all tasks") |
There was a problem hiding this comment.
🩺 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.
| 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.
| 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 |
There was a problem hiding this comment.
📐 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.
| 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 |
There was a problem hiding this comment.
🎯 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") |
There was a problem hiding this comment.
🎯 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.
| 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.
Summary
As title.