Documentation
¶
Overview ¶
Example (ErrorCodes) ¶
Example_errorCodes demonstrates using error code constants.
// Create errors using constructors (they use the constants internally)
err := ErrServiceNotFound("database")
// You can access the code constant for custom logic
var forgeErr *ForgeError
if As(err, &forgeErr) {
switch forgeErr.Code {
case CodeServiceNotFound:
fmt.Println("Service not found")
case CodeServiceAlreadyExists:
fmt.Println("Service already exists")
case CodeCircularDependency:
fmt.Println("Circular dependency")
}
}
// Using sentinel errors for comparison
if Is(err, ErrServiceNotFoundSentinel) {
fmt.Println("Matched using sentinel")
}
// Using helper functions
if IsServiceNotFound(err) {
fmt.Println("Matched using helper")
}
Output: Service not found Matched using sentinel Matched using helper
Example (ErrorConstants) ¶
Example_errorConstants demonstrates the available error code constants.
// All available error code constants:
codes := []string{
CodeConfigError, // "CONFIG_ERROR"
CodeValidationError, // "VALIDATION_ERROR"
CodeLifecycleError, // "LIFECYCLE_ERROR"
CodeContextCancelled, // "CONTEXT_CANCELLED"
CodeServiceNotFound, // "SERVICE_NOT_FOUND"
CodeServiceAlreadyExists, // "SERVICE_ALREADY_EXISTS"
CodeCircularDependency, // "CIRCULAR_DEPENDENCY"
CodeInvalidConfig, // "INVALID_CONFIG"
CodeTimeoutError, // "TIMEOUT_ERROR"
}
for _, code := range codes {
fmt.Printf("Code: %s\n", code)
}
Output: Code: CONFIG_ERROR Code: VALIDATION_ERROR Code: LIFECYCLE_ERROR Code: CONTEXT_CANCELLED Code: SERVICE_NOT_FOUND Code: SERVICE_ALREADY_EXISTS Code: CIRCULAR_DEPENDENCY Code: INVALID_CONFIG Code: TIMEOUT_ERROR
Example (ErrorMatching) ¶
Example_errorMatching demonstrates various error matching patterns.
// Create a wrapped error chain
baseErr := ErrServiceNotFound("auth")
wrappedErr := ErrConfigError("failed to initialize", baseErr)
// Match by code using Is with sentinel
if Is(wrappedErr, ErrServiceNotFoundSentinel) {
fmt.Println("Found SERVICE_NOT_FOUND in chain")
}
// Match by code using Is with a new error instance
if Is(wrappedErr, &ForgeError{Code: CodeConfigError}) {
fmt.Println("Found CONFIG_ERROR in chain")
}
// Extract specific error type using As
var configErr *ForgeError
if As(wrappedErr, &configErr) {
if configErr.Code == CodeConfigError {
fmt.Println("Top-level error is CONFIG_ERROR")
}
}
Output: Found SERVICE_NOT_FOUND in chain Found CONFIG_ERROR in chain Top-level error is CONFIG_ERROR
Example (ForgeErrorWithConstants) ¶
Example_forgeErrorWithConstants shows creating custom ForgeErrors with constants.
// When creating custom ForgeErrors, use the constants
customErr := &ForgeError{
Code: CodeValidationError,
Message: "custom validation failed",
}
// Add context
customErr.WithContext("field", "email").WithContext("rule", "format")
// Check error type
if Is(customErr, ErrValidationErrorSentinel) {
fmt.Println("This is a validation error")
}
Output: This is a validation error
Index ¶
- Constants
- Variables
- func As(err error, target any) bool
- func GetHTTPStatusCode(err error) int
- func Is(err, target error) bool
- func IsCircularDependency(err error) bool
- func IsContextCancelled(err error) bool
- func IsServiceAlreadyExists(err error) bool
- func IsServiceNotFound(err error) bool
- func IsTimeout(err error) bool
- func IsValidationError(err error) bool
- func Join(errs ...error) error
- func New(text string) error
- func Unwrap(err error) error
- type ForgeError
- func ErrCircularDependency(services []string) *ForgeError
- func ErrConfigError(message string, cause error) *ForgeError
- func ErrContainerError(operation string, cause error) *ForgeError
- func ErrContextCancelled(operation string) *ForgeError
- func ErrDependencyNotFound(deps ...string) *ForgeError
- func ErrHealthCheckFailed(serviceName string, cause error) *ForgeError
- func ErrInvalidConfig(configKey string, cause error) *ForgeError
- func ErrLifecycleError(phase string, cause error) *ForgeError
- func ErrServiceAlreadyExists(serviceName string) *ForgeError
- func ErrServiceNotFound(serviceName string) *ForgeError
- func ErrServiceStartFailed(serviceName string, cause error) *ForgeError
- func ErrTimeoutError(operation string, timeout time.Duration) *ForgeError
- func ErrValidationError(field string, cause error) *ForgeError
- type HTTPError
- type ServiceError
- type Severity
- type ValidationError
Examples ¶
Constants ¶
const ( CodeConfigError = "CONFIG_ERROR" CodeValidationError = "VALIDATION_ERROR" CodeLifecycleError = "LIFECYCLE_ERROR" CodeContextCancelled = "CONTEXT_CANCELLED" CodeServiceNotFound = "SERVICE_NOT_FOUND" CodeServiceAlreadyExists = "SERVICE_ALREADY_EXISTS" CodeCircularDependency = "CIRCULAR_DEPENDENCY" CodeInvalidConfig = "INVALID_CONFIG" CodeTimeoutError = "TIMEOUT_ERROR" CodeHealthCheckFailed = "HEALTH_CHECK_FAILED" CodeServiceStartFailed = "SERVICE_START_FAILED" )
Error code constants for structured errors.
Variables ¶
var ( // ErrServiceNotFound = errors.New("service not found") // ErrServiceAlreadyExists = errors.New("service already registered") // ErrCircularDependency = errors.New("circular dependency detected"). ErrInvalidFactory = errors.New("factory must be a function") ErrTypeMismatch = errors.New("service type mismatch") ErrLifecycleTimeout = errors.New("lifecycle operation timed out") ErrContainerStarted = errors.New("container already started") ErrContainerStopped = errors.New("container already stopped") ErrScopeEnded = errors.New("scope already ended") )
Standard DI/service errors.
var ( // ErrServiceNotFoundSentinel is a sentinel error for service not found. ErrServiceNotFoundSentinel = &ForgeError{Code: CodeServiceNotFound} // ErrServiceAlreadyExistsSentinel is a sentinel error for service already exists. ErrServiceAlreadyExistsSentinel = &ForgeError{Code: CodeServiceAlreadyExists} // ErrCircularDependencySentinel is a sentinel error for circular dependency. ErrCircularDependencySentinel = &ForgeError{Code: CodeCircularDependency} // ErrInvalidConfigSentinel is a sentinel error for invalid config. ErrInvalidConfigSentinel = &ForgeError{Code: CodeInvalidConfig} // ErrValidationErrorSentinel is a sentinel error for validation errors. ErrValidationErrorSentinel = &ForgeError{Code: CodeValidationError} // ErrLifecycleErrorSentinel is a sentinel error for lifecycle errors. ErrLifecycleErrorSentinel = &ForgeError{Code: CodeLifecycleError} // ErrContextCancelledSentinel is a sentinel error for context cancellation. ErrContextCancelledSentinel = &ForgeError{Code: CodeContextCancelled} // ErrTimeoutErrorSentinel is a sentinel error for timeout errors. ErrTimeoutErrorSentinel = &ForgeError{Code: CodeTimeoutError} // ErrConfigErrorSentinel is a sentinel error for config errors. ErrConfigErrorSentinel = &ForgeError{Code: CodeConfigError} )
Sentinel errors that can be used with errors.Is comparisons.
Functions ¶
func As ¶
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true. Otherwise, it returns false. This is a convenience wrapper around errors.As from the standard library.
Example:
var httpErr *HTTPError
if As(err, &httpErr) {
// handle HTTP error with httpErr.Code
}
Example ¶
Example showing error unwrapping.
// Create a wrapped error
innerErr := BadRequest("invalid input")
wrappedErr := ErrConfigError("config failed", innerErr)
// Extract the HTTPError from the chain
var httpErr *HTTPError
if As(wrappedErr, &httpErr) {
// Use the extracted error
statusCode := httpErr.Code
_ = statusCode
}
func GetHTTPStatusCode ¶
GetHTTPStatusCode extracts HTTP status code from error, returns 500 if not found.
func Is ¶
Is reports whether any error in err's chain matches target. This is a convenience wrapper around errors.Is from the standard library.
Example:
err := ErrServiceNotFound("auth")
if Is(err, &ForgeError{Code: "SERVICE_NOT_FOUND"}) {
// handle service not found
}
Example ¶
Example usage demonstrating the new Is functionality.
// Create an error
err := ErrServiceNotFound("database")
// Check using Is with sentinel error
if Is(err, ErrServiceNotFoundSentinel) {
// Handle service not found
}
// Or use the convenience helper
if IsServiceNotFound(err) {
// Handle service not found
}
func IsCircularDependency ¶
IsCircularDependency checks if the error is a circular dependency error.
func IsContextCancelled ¶
IsContextCancelled checks if the error is a context cancelled error.
func IsServiceAlreadyExists ¶
IsServiceAlreadyExists checks if the error is a service already exists error.
func IsServiceNotFound ¶
IsServiceNotFound checks if the error is a service not found error.
func IsValidationError ¶
IsValidationError checks if the error is a validation error.
func Join ¶
Join returns an error that wraps the given errors. Any nil error values are discarded. This is a convenience wrapper around errors.Join from the standard library. Requires Go 1.20+.
Types ¶
type ForgeError ¶
type ForgeError struct {
Code string
Message string
Cause error
Timestamp time.Time
Context map[string]any
}
ForgeError represents a structured error with context.
func ErrCircularDependency ¶
func ErrCircularDependency(services []string) *ForgeError
func ErrConfigError ¶
func ErrConfigError(message string, cause error) *ForgeError
ErrConfigError creates a config error.
func ErrContainerError ¶
func ErrContainerError(operation string, cause error) *ForgeError
func ErrContextCancelled ¶
func ErrContextCancelled(operation string) *ForgeError
func ErrDependencyNotFound ¶
func ErrDependencyNotFound(deps ...string) *ForgeError
func ErrHealthCheckFailed ¶
func ErrHealthCheckFailed(serviceName string, cause error) *ForgeError
func ErrInvalidConfig ¶
func ErrInvalidConfig(configKey string, cause error) *ForgeError
func ErrLifecycleError ¶
func ErrLifecycleError(phase string, cause error) *ForgeError
ErrLifecycleError creates a lifecycle error.
func ErrServiceAlreadyExists ¶
func ErrServiceAlreadyExists(serviceName string) *ForgeError
func ErrServiceNotFound ¶
func ErrServiceNotFound(serviceName string) *ForgeError
func ErrServiceStartFailed ¶
func ErrServiceStartFailed(serviceName string, cause error) *ForgeError
func ErrTimeoutError ¶
func ErrTimeoutError(operation string, timeout time.Duration) *ForgeError
func ErrValidationError ¶
func ErrValidationError(field string, cause error) *ForgeError
ErrValidationError creates a validation error.
func (*ForgeError) Error ¶
func (e *ForgeError) Error() string
func (*ForgeError) Is ¶
func (e *ForgeError) Is(target error) bool
Is implements errors.Is interface for ForgeError Compares by error code, allowing matching against sentinel errors.
func (*ForgeError) ResponseBody ¶
func (e *ForgeError) ResponseBody() any
ResponseBody returns the response body (implements shared.HTTPResponder)
func (*ForgeError) StatusCode ¶
func (e *ForgeError) StatusCode() int
StatusCode returns 500 for ForgeError (implements shared.HTTPResponder)
func (*ForgeError) Unwrap ¶
func (e *ForgeError) Unwrap() error
func (*ForgeError) WithContext ¶
func (e *ForgeError) WithContext(key string, value any) *ForgeError
WithContext adds context to the error.
type HTTPError ¶
HTTPError represents an HTTP error with status code.
func BadRequest ¶
func InternalError ¶
func Unauthorized ¶
func (*HTTPError) Is ¶
Is implements errors.Is interface for HTTPError Compares by HTTP status code.
func (*HTTPError) ResponseBody ¶
ResponseBody returns the response body (implements shared.HTTPResponder)
func (*HTTPError) StatusCode ¶
StatusCode returns the HTTP status code (implements shared.HTTPResponder)
type ServiceError ¶
ServiceError wraps service-specific errors.
func NewServiceError ¶
func NewServiceError(service, operation string, err error) *ServiceError
NewServiceError creates a new service error.
func (*ServiceError) Error ¶
func (e *ServiceError) Error() string
func (*ServiceError) Is ¶
func (e *ServiceError) Is(target error) bool
Is implements errors.Is interface for ServiceError.
func (*ServiceError) Unwrap ¶
func (e *ServiceError) Unwrap() error
type ValidationError ¶
type ValidationError struct {
Key string `json:"key"`
Value any `json:"value,omitempty"`
Rule string `json:"rule"`
Message string `json:"message"`
Severity Severity `json:"severity"`
Suggestion string `json:"suggestion,omitempty"`
}
ValidationError represents a validation error.