Debian Codegraph @

internal/failures/failure.go

raw
1 // Package failures provides a structured error handling mechanism with unique identifiers
2 // for categorizing and identifying different error types. It implements the Failure interface
3 // to support Go's error wrapping conventions, allowing for rich error chaining and comparison.
4 package failures
5
6 import "fmt"
7
8 // FailureID is a unique identifier for a specific error type.
9 type FailureID int
10
11 // failure is the concrete implementation of the Failure interface.
12 // It wraps an error with a message and an ID for categorization.
13 type failure struct {
14 message string // Descriptive message for the error
15 id FailureID // Unique identifier for this error type
16 wrapped error // Underlying error, if any, for chaining
17 }
18
19 // Failure extends the error interface with an ID and methods for unwrapping and comparison.
20 // It allows errors to be identified by a unique ID and supports Go's error wrapping conventions.
21 type Failure interface {
22 error
23 ID() FailureID // Returns the unique identifier for this failure
24 Unwrap() error // Returns the wrapped error, if any
25 Is(target error) bool // Checks if the target error matches this failure by ID
26 }
27
28 // Ensure failure implements the error interface at compile time.
29 //
30 //nolint:errcheck // Compile-time type assertion, not an error check
31 var _ error = (*failure)(nil)
32
33 // Error returns the failure's message, appending the wrapped error's message if present.
34 func (f *failure) Error() string {
35 if f.wrapped == nil {
36 return f.message
37 }
38
39 return fmt.Sprintf("%s: %v", f.message, f.wrapped)
40 }
41
42 // ID returns the unique identifier assigned to this failure.
43 func (f *failure) ID() FailureID {
44 return f.id
45 }
46
47 // Is reports whether the target error is a failure with the same ID.
48 // It only returns true for failures of the same type with matching IDs.
49 func (f *failure) Is(target error) bool {
50 targetFailure, ok := target.(*failure)
51
52 return ok && targetFailure.id == f.id
53 }
54
55 // Unwrap returns the underlying error wrapped by this failure, or nil if none exists.
56 func (f *failure) Unwrap() error {
57 return f.wrapped
58 }
59
60 // Wrap creates a new failure with the given message, ID, and optional wrapped error.
61 // If variadic arguments are provided, they are used to format the message using fmt.Sprintf.
62 // This supports Go's error wrapping pattern while adding a unique ID for identification.
63 func Wrap(message string, failureID FailureID, wrappedError error, v ...any) Failure {
64 if len(v) > 0 {
65 message = fmt.Sprintf(message, v...)
66 }
67
68 return &failure{
69 message: message,
70 id: failureID,
71 wrapped: wrappedError,
72 }
73 }