Repository navigation
feat: add validation error to models - #2838
Conversation
📝 WalkthroughWalkthroughThe changes introduce a structured error and validation issue framework in the Changes
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 ✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (7)
pkg/models/error.go (2)
300-306:Valuesshould be a standalone helper, not a method onErrorSeverity.Declaring
Values()with a receiver requires an (unused) zero-value ofErrorSeverityjust to call it:var all = ErrorSeverity("").Values()A plain function avoids that oddness and makes intent clearer:
-func (s ErrorSeverity) Values() []string { +func ErrorSeverityValues() []string {This also prevents accidental shadowing of the receiver variable and saves one unnecessary allocation for the receiver copy.
312-320:FieldPathFromPartslacks a doc-comment and the semantics for absolute segments may surprise callers.
- Public helpers in
pkg/modelsshould begin with a Go-style doc comment so thatgo doc/IDE tooling can surface them.- If any part starts with
/, previous segments are silently discarded (path.Joinbehaviour). That’s fine for the current tests, but callers might expect/prefixto be preserved.Consider adding a short comment explaining this reset rule or, if unintended, prepend
strings.TrimPrefix(part, "/")to every part before joining.pkg/models/validationissue_test.go (2)
109-143: Duplicate sub-test names make debugging harder.There are two cases both named
"mixed". While Go allows this, test output collapses under the same label, complicating failure triage. Rename them to something unique, e.g."mixed/no-issues"and"mixed/no-extraction".
221-264: Order-sensitive comparison may introduce flaky tests.
ValidationIssuesis a slice, butAsValidationIssueswalks an error-tree where traversal order isn’t guaranteed by the language.
Usingrequire.Equalasserts exact ordering; a different traversal (e.g., when join order changes) would fail even though the content is identical.Prefer an order-insensitive assert:
- require.Equalf(t, test.expectedIssues, actual, "issues must match") + assert.ElementsMatchf(t, test.expectedIssues, actual, "issues must match (order-independent)")This keeps the check strict on membership/content while avoiding brittle ordering expectations.
pkg/models/validationissue.go (3)
54-58: Defensive copy to prevent unexpected mutations
WithAttributesstores the caller-provided map pointer directly. Because maps are reference types, any later mutation of the original map will change theValidationIssuein place – potentially long after it has been handed off to another goroutine.func WithAttributes(attrs map[string]interface{}) ValidationIssueOption { return func(i *ValidationIssue) { - i.Attributes = attrs + if attrs == nil { + return + } + clone := make(map[string]interface{}, len(attrs)) + for k, v := range attrs { + clone[k] = v + } + i.Attributes = clone } }The shallow copy is cheap and avoids hard-to-trace data races or heisenbugs.
86-98: Consider assigning an explicit default severity
NewValidationIssueleavesSeverityempty unless an option is supplied. Callers may forget to set one, producing issues whose criticality is ambiguous and forcing downstream code to handle the “empty” case.Two alternatives:
- Pick a sensible default, e.g.
ErrorSeverityCritical.- Return an error (or panic in tests) if no severity option is provided, making the omission explicit.
Either approach will make the API harder to misuse.
207-222: Remove unnecessary generic type parameter inEncodeValidationIssues
EncodeValidationIssues[T error]never uses the type parameterT; accepting a plainerroris sufficient and avoids the extra type inference step for callers (especially in Go <1.22 where type-set inference is still evolving).-func EncodeValidationIssues[T error](err T) map[string]interface{} { +func EncodeValidationIssues(err error) map[string]interface{} {Behaviour remains identical while the signature becomes simpler.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
pkg/models/error.go(2 hunks)pkg/models/error_test.go(1 hunks)pkg/models/validationissue.go(1 hunks)pkg/models/validationissue_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/models/validationissue_test.go (2)
pkg/models/validationissue.go (11)
ValidationIssue(11-18)ValidationIssues(110-110)NewValidationError(101-103)NewValidationWarning(106-108)NewValidationIssue(87-98)WithPath(66-70)WithCriticalSeverity(78-80)WithWarningSeverity(82-84)WithAttributes(54-58)WithComponent(60-64)AsValidationIssues(129-140)pkg/models/error.go (4)
ErrorSeverityCritical(308-308)ErrorSeverityWarning(309-309)ErrorWithComponent(359-365)ErrorWithFieldPrefix(336-342)
⏰ Context from checks skipped due to timeout of 90000ms (13)
- GitHub Check: Artifacts / Container image
- GitHub Check: Artifacts / Benthos Collector Container image
- GitHub Check: Test
- GitHub Check: Quickstart
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Build
- GitHub Check: Analyze (javascript)
- GitHub Check: Analyze (go)
🔇 Additional comments (1)
pkg/models/error_test.go (1)
1-40: Nice coverage for tricky path combinations.The test suite thoroughly exercises empty, multiple, unclean and traversal cases – good job!
d8bd559 to
af4227d
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
pkg/models/validationissue_test.go (1)
256-267: Error comparison could be improvedAs noted in a previous review comment, using
require.Equalfor error comparison relies onreflect.DeepEqualwhich checks pointer equality for errors. This can lead to false negatives when comparing semantically identical errors with different instances.Consider using
errors.Is()for error comparison whentest.expectErroris true:if test.expectError { - require.EqualErrorf(t, err, test.err.Error(), "error must match") + require.Errorf(t, err, "expected an error") + require.ErrorIsf(t, err, test.err, "error must match expected type") } else { require.NoError(t, err, "error must be nil") }
🧹 Nitpick comments (3)
pkg/models/validationissue_test.go (3)
109-131: Duplicate test case name "mixed"There are two test cases with the same name "mixed" (lines 109-119 and 121-131) with identical content. This duplication could lead to confusion when interpreting test failures.
{ - name: "mixed", + name: "mixed duplicate", err: fmt.Errorf("test: %w", errors.Join( errors.New("error 1"), NewValidationError("errcode1", "error message 1"), NewValidationWarning("errcode2", "error message 2"), ), ), expectError: true, expectedIssues: nil, },
271-286: Round-trip validation test could be more comprehensiveThe round-trip test (
TestValidationIssues_AsError) only tests a single validation issue. Consider extending this test to include multiple validation issues with various attributes to ensure the round-trip conversion works correctly in all scenarios.func TestValidationIssues_AsError(t *testing.T) { - issues := ValidationIssues{ - { - Severity: ErrorSeverityCritical, - Message: "error1", - Component: "component1", - Path: "/some/path/from/component1", - }, - } + tests := []struct { + name string + issues ValidationIssues + }{ + { + name: "single issue", + issues: ValidationIssues{ + { + Severity: ErrorSeverityCritical, + Message: "error1", + Component: "component1", + Path: "/some/path/from/component1", + }, + }, + }, + { + name: "multiple issues", + issues: ValidationIssues{ + { + Severity: ErrorSeverityCritical, + Message: "error1", + Component: "component1", + Path: "/some/path/from/component1", + }, + { + Code: "code2", + Severity: ErrorSeverityWarning, + Message: "error2", + Component: "component2", + Path: "/path2", + Attributes: map[string]interface{}{ + "attr": "value", + }, + }, + }, + }, + } - err := issues.AsError() - - validationIssues, err := AsValidationIssues(err) - require.NoError(t, err) - require.Equal(t, issues, validationIssues) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.issues.AsError() + + validationIssues, err := AsValidationIssues(err) + require.NoError(t, err) + require.Equal(t, tt.issues, validationIssues) + }) + } }
83-269: Consider adding test cases for error codes and messagesThe test cases for
AsValidationIssuesare comprehensive for nested structures, but could benefit from explicit tests verifying that error codes and messages are correctly preserved when converting between error types.You might want to add a test case specifically focused on verifying that custom error codes are properly extracted and preserved:
{ name: "custom error code", err: NewValidationIssue("custom_code", "custom message", WithCriticalSeverity(), WithComponent("test_component")), expectError: false, expectedIssues: ValidationIssues{ ValidationIssue{ Code: "custom_code", Message: "custom message", Component: "test_component", Severity: ErrorSeverityCritical, }, }, },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
pkg/models/error.go(2 hunks)pkg/models/error_test.go(1 hunks)pkg/models/validationissue.go(1 hunks)pkg/models/validationissue_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- pkg/models/error_test.go
- pkg/models/validationissue.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
pkg/models/validationissue_test.go (2)
pkg/models/validationissue.go (11)
ValidationIssue(11-18)ValidationIssues(115-115)NewValidationError(106-108)NewValidationWarning(111-113)NewValidationIssue(92-103)WithPath(71-75)WithCriticalSeverity(83-85)WithWarningSeverity(87-89)WithAttributes(59-63)WithComponent(65-69)AsValidationIssues(134-145)openmeter/ent/db/billinginvoicevalidationissue/where.go (2)
Path(105-107)Component(110-112)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Analyze (go)
- GitHub Check: Build
- GitHub Check: Lint
🔇 Additional comments (5)
pkg/models/error.go (4)
291-311: Well-structured error type system with appropriate constantsThe added types (
ComponentName,ErrorCode,ErrorSeverity) and constants provide a strong foundation for standardized error classification across the codebase. The enumeration of severity values through theValues()method is a good practice for validation or documentation purposes.
313-321: Path construction approach looks goodThe
FieldPathFromPartsfunction creates standardized paths using thepathpackage, ensuring consistent path representation with a leading slash. This method properly handles empty paths as well.
323-347: Error prefix wrapper follows Go error composition patternThe
fieldPrefixedWrappertype andErrorWithFieldPrefixfunction correctly implement the error wrapping pattern by supportingUnwrap(). The implementation correctly handles nil errors and provides clear error messages with appropriate formatting.
349-370: Component error wrapper follows best practicesThe
componentWrappertype andErrorWithComponentfunction provide a clean way to add component context to errors. The implementation properly handles nil errors and follows Go's error wrapping conventions.pkg/models/validationissue_test.go (1)
13-81: Well-structured JSON serialization testsThe tests comprehensively verify
ValidationIssueJSON serialization with various field combinations. The test cases cover empty issues, basic issues, and issues with all fields populated.
Overview
Standardize validation errors by reusing code from
billingpackage.Summary by CodeRabbit