-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
99 lines (81 loc) · 2.55 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package sage
import (
"errors"
"fmt"
)
var (
// ErrInvalidOperation indicates an invalid database operation
ErrInvalidOperation = errors.New("invalid database operation")
// ErrInvalidArgument indicates an invalid argument
ErrInvalidArgument = errors.New("invalid argument")
// ErrConnectionFailed indicates a connection failure
ErrConnectionFailed = errors.New("database connection failed")
// ErrTransactionFailed indicates a transaction failure
ErrTransactionFailed = errors.New("transaction failed")
// ErrUnsupportedDriver indicates an unsupported database driver
ErrUnsupportedDriver = errors.New("unsupported database driver")
// ErrMigrationFailed indicates a migration failure
ErrMigrationFailed = errors.New("migration failed")
)
// WrapError wraps an error with additional context
func WrapError(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
message := fmt.Sprintf(format, args...)
return fmt.Errorf("%s: %w", message, err)
}
// IsNotFoundError checks if an error is ErrNotFound
func IsNotFoundError(err error) bool {
return errors.Is(err, ErrNotFound)
}
// IsValidationError checks if an error is a validation error
func IsValidationError(err error) bool {
var valErr *ValidationError
return errors.As(err, &valErr)
}
// ValidationError represents validation errors for a model
type ValidationError struct {
Field string
Message string
}
// Error returns the error message
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation error on field %s: %s", e.Field, e.Message)
}
// NewValidationError creates a new validation error
func NewValidationError(field, message string) *ValidationError {
return &ValidationError{
Field: field,
Message: message,
}
}
// ValidationErrors represents multiple validation errors
type ValidationErrors struct {
Errors []*ValidationError
}
// Error returns all error messages joined together
func (e *ValidationErrors) Error() string {
message := "validation errors: "
for i, err := range e.Errors {
if i > 0 {
message += "; "
}
message += err.Error()
}
return message
}
// AddError adds a validation error
func (e *ValidationErrors) AddError(field, message string) {
e.Errors = append(e.Errors, NewValidationError(field, message))
}
// HasErrors checks if there are any validation errors
func (e *ValidationErrors) HasErrors() bool {
return len(e.Errors) > 0
}
// NewValidationErrors creates a new validation errors container
func NewValidationErrors() *ValidationErrors {
return &ValidationErrors{
Errors: make([]*ValidationError, 0),
}
}