Skip to content

feat: add validation error to models - #2838

Merged
chrisgacsal merged 1 commit into
mainfrom
refactor/validation-errors
May 19, 2025
Merged

chrisgacsal merged 1 commit into
mainfrom
refactor/validation-errors

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented May 19, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Standardize validation errors by reusing code from billing package.

Summary by CodeRabbit

  • New Features
    • Introduced structured validation error handling with support for error codes, severity levels, component tagging, and field path context.
    • Added utilities for constructing, wrapping, extracting, and encoding validation issues with rich metadata.
  • Tests
    • Added comprehensive unit tests for validation error creation, extraction, serialization, and round-trip conversion.
  • Chores
    • Enhanced error context and classification throughout the validation framework.

@chrisgacsal chrisgacsal self-assigned this May 19, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner May 19, 2025 03:58
@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label May 19, 2025
@coderabbitai

coderabbitai Bot commented May 19, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes introduce a structured error and validation issue framework in the pkg/models package. New types and utilities for error context, severity, and component tracking are added, along with comprehensive error-wrapping and extraction mechanisms. Extensive tests validate path construction, error wrapping, validation issue creation, JSON serialization, and error-to-issue conversion.

Changes

File(s) Change Summary
pkg/models/error.go Introduced new string types (ComponentName, ErrorCode, ErrorSeverity), severity constants, and a method to list severity values. Added FieldPathFromParts for normalized path construction. Added error wrappers (fieldPrefixedWrapper, componentWrapper) and helper functions to wrap errors with field prefixes or component names, implementing standard error interfaces.
pkg/models/error_test.go Added unit tests for FieldPathFromParts, validating path normalization across multiple scenarios including empty input, single/multiple parts, redundant slashes, dot segments, and path traversal.
pkg/models/validationissue.go Added ValidationIssue struct with metadata fields and error interface implementation. Provided functional options for setting attributes, component, path, and severity. Added constructors for validation errors and warnings. Defined ValidationIssues slice with cloning and error aggregation methods. Implemented AsValidationIssues to recursively extract validation issues from arbitrary errors, handling wrappers and unknown errors. Added EncodeValidationIssues to serialize validation issues into a map.
pkg/models/validationissue_test.go Added comprehensive tests for ValidationIssue JSON serialization, AsValidationIssues error extraction logic (covering nil, wrapped, joined, and nested errors), and round-trip conversion tests for ValidationIssues.AsError.

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
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 2

🧹 Nitpick comments (7)
pkg/models/error.go (2)

300-306: Values should be a standalone helper, not a method on ErrorSeverity.

Declaring Values() with a receiver requires an (unused) zero-value of ErrorSeverity just 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: FieldPathFromParts lacks a doc-comment and the semantics for absolute segments may surprise callers.

  1. Public helpers in pkg/models should begin with a Go-style doc comment so that go doc/IDE tooling can surface them.
  2. If any part starts with /, previous segments are silently discarded (path.Join behaviour). That’s fine for the current tests, but callers might expect /prefix to 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.

ValidationIssues is a slice, but AsValidationIssues walks an error-tree where traversal order isn’t guaranteed by the language.
Using require.Equal asserts 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

WithAttributes stores the caller-provided map pointer directly. Because maps are reference types, any later mutation of the original map will change the ValidationIssue in 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

NewValidationIssue leaves Severity empty 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:

  1. Pick a sensible default, e.g. ErrorSeverityCritical.
  2. 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 in EncodeValidationIssues

EncodeValidationIssues[T error] never uses the type parameter T; accepting a plain error is 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

📥 Commits

Reviewing files that changed from the base of the PR and between b694510 and d8bd559.

📒 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!

Comment thread pkg/models/validationissue_test.go Resolved
Comment thread pkg/models/validationissue.go Resolved
turip
turip previously approved these changes May 19, 2025

@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: 0

♻️ Duplicate comments (1)
pkg/models/validationissue_test.go (1)

256-267: Error comparison could be improved

As noted in a previous review comment, using require.Equal for error comparison relies on reflect.DeepEqual which 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 when test.expectError is 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 comprehensive

The 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 messages

The test cases for AsValidationIssues are 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

📥 Commits

Reviewing files that changed from the base of the PR and between d8bd559 and af4227d.

📒 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 constants

The added types (ComponentName, ErrorCode, ErrorSeverity) and constants provide a strong foundation for standardized error classification across the codebase. The enumeration of severity values through the Values() method is a good practice for validation or documentation purposes.


313-321: Path construction approach looks good

The FieldPathFromParts function creates standardized paths using the path package, 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 pattern

The fieldPrefixedWrapper type and ErrorWithFieldPrefix function correctly implement the error wrapping pattern by supporting Unwrap(). The implementation correctly handles nil errors and provides clear error messages with appropriate formatting.


349-370: Component error wrapper follows best practices

The componentWrapper type and ErrorWithComponent function 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 tests

The tests comprehensively verify ValidationIssue JSON serialization with various field combinations. The test cases cover empty issues, basic issues, and issues with all fields populated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants