Documentation
¶
Overview ¶
Package errmgr provides common error definitions and categories for use across applications. These predefined errors are designed for consistency in error handling and can be used directly as immutable instances or copied for customization using Copy().
Package errmgr provides functionality for managing error templates, counts, thresholds, and alerts in a thread-safe manner, building on the core errors package.
Package errmgr provides error monitoring functionality.
Index ¶
- Constants
- Variables
- func Categorized(category errors.ErrorCategory, name, template string) func(...interface{}) *errors.Error
- func CloseMonitor(name string)
- func Coded(name, template string, code int) func(...interface{}) *errors.Error
- func Configure(cfg Config)
- func Copy(err *errors.Error) *errors.Error
- func Define(name, template string) func(...interface{}) *errors.Error
- func GetThreshold(name string) (uint64, bool)
- func Metrics() map[string]uint64
- func RemoveThreshold(name string)
- func Reset()
- func ResetCounter(name string)
- func SetThreshold(name string, threshold uint64)
- func Tracked(name string, fn func(...interface{}) *errors.Error) func(...interface{}) *errors.Error
- type Config
- type Monitor
Constants ¶
const ( CategoryAuth errors.ErrorCategory = "auth" // Authentication-related errors (e.g., login failures) CategoryBusiness errors.ErrorCategory = "business" // Business logic errors (e.g., rule violations) CategoryDatabase errors.ErrorCategory = "database" // Database-related errors (e.g., connection issues) CategoryIO errors.ErrorCategory = "io" // Input/Output-related errors (e.g., file operations) CategoryNetwork errors.ErrorCategory = "network" // Network-related errors (e.g., timeouts, unreachable hosts) CategorySystem errors.ErrorCategory = "system" // System-level errors (e.g., resource exhaustion) CategoryUser errors.ErrorCategory = "user" // User-related errors (e.g., invalid input, permissions) CategoryValidation errors.ErrorCategory = "validation" // Validation-related errors (e.g., invalid input formats) )
Common error categories used for organizing errors across different domains.
const ( CodeBadRequest = 400 // HTTP 400 Bad Request (client error, invalid input) CodeForbidden = 403 // HTTP 403 Forbidden (access denied) CodeNotFound = 404 // HTTP 404 Not Found (resource not found) CodeMethodNotAllowed = 405 // HTTP 405 Method Not Allowed (unsupported method) CodeConflict = 409 // HTTP 409 Conflict (resource conflict) CodeUnprocessable = 422 // HTTP 422 Unprocessable Entity (semantic errors in request) CodeTooManyRequests = 429 // HTTP 429 Too Many Requests (rate limiting) CodeInternalError = 500 // HTTP 500 Internal Server Error (server failure) CodeNotImplemented = 501 // HTTP 501 Not Implemented (feature not supported) )
Common HTTP status codes used for error responses, aligned with REST API conventions.
Variables ¶
var ( ErrInvalidArg = errors.New("invalid argument").WithCode(CodeBadRequest) ErrNotFound = errors.New("not found").WithCode(CodeNotFound) ErrPermission = errors.New("permission denied").WithCode(CodeForbidden) ErrTimeout = errors.New("operation timed out").WithTimeout() ErrUnknown = errors.New("unknown error").WithCode(CodeInternalError) ErrDBConnRetryable = errors.New("database connection failed").WithCategory(CategoryDatabase).WithRetryable() ErrNetworkRetryable = errors.New("network failure").WithCategory(CategoryNetwork).WithRetryable() ErrNetworkTimedOut = errors.New("network timeout").WithCategory(CategoryNetwork).WithTimeout().WithRetryable() ErrServiceRetryable = errors.New("service unavailable").WithCode(CodeServiceUnavailable).WithRetryable() ErrRateLimitRetryable = errors.New("rate limit exceeded").WithCode(CodeTooManyRequests).WithRetryable() )
Generic Predefined Errors (Static) These are immutable instances suitable for direct use or copying with Copy(). Errors requiring specific properties like WithRetryable() or WithTimeout() are defined here.
var ( ErrAuthFailed = Coded("ErrAuthFailed", "authentication failed for %s: %s", CodeUnauthorized) ErrInvalidToken = Coded("ErrInvalidToken", "invalid authentication token: %s", CodeUnauthorized) ErrMissingCreds = Coded("ErrMissingCreds", "missing credentials: %s", CodeBadRequest) ErrTokenExpired = Coded("ErrTokenExpired", "authentication token expired: %s", CodeUnauthorized) )
Authentication Errors (Templated) Use these by providing arguments, e.g., ErrAuthFailed("user@example.com", "invalid password").
var ( ErrBusinessRule = Categorized(CategoryBusiness, "ErrBusinessRule", "business rule violation: %s") ErrInsufficientFunds = Categorized(CategoryBusiness, "ErrInsufficientFunds", "insufficient funds: %s") )
Business Logic Errors (Templated) Example: ErrInsufficientFunds("account123", "balance too low").
var ( ErrDBConnection = Categorized(CategoryDatabase, "ErrDBConnection", "database connection failed: %s") ErrDBConstraint = Coded("ErrDBConstraint", "database constraint violation: %s", CodeConflict) ErrDBQuery = Categorized(CategoryDatabase, "ErrDBQuery", "database query failed: %s") ErrDBTimeout = Categorized(CategoryDatabase, "ErrDBTimeout", "database operation timed out: %s") )
Database Errors (Templated) Example: ErrDBConnection("mysql", "host unreachable").
var ( ErrFileNotFound = Coded("ErrFileNotFound", "file (%s) not found", CodeNotFound) ErrIORead = Categorized(CategoryIO, "ErrIORead", "I/O read error: %s") ErrIOWrite = Categorized(CategoryIO, "ErrIOWrite", "I/O write error: %s") )
IO Errors (Templated) Example: ErrFileNotFound("/path/to/file").
var ( ErrNetworkConnRefused = Categorized(CategoryNetwork, "ErrNetworkConnRefused", "connection refused: %s") ErrNetworkTimeout = Categorized(CategoryNetwork, "ErrNetworkTimeout", "network timeout: %s") ErrNetworkUnreachable = Categorized(CategoryNetwork, "ErrNetworkUnreachable", "network unreachable: %s") )
Network Errors (Templated) Example: ErrNetworkTimeout("http://example.com", "no response").
var ( ErrConfigInvalid = Coded("ErrConfigInvalid", "invalid configuration: %s", CodeInternalError) ErrResourceExhausted = Coded("ErrResourceExhausted", "resource exhausted: %s", CodeServiceUnavailable) ErrSystemFailure = Coded("ErrSystemFailure", "system failure: %s", CodeInternalError) ErrSystemUnhealthy = Coded("ErrSystemUnhealthy", "system unhealthy: %s", CodeServiceUnavailable) )
System Errors (Templated) Example: ErrResourceExhausted("memory", "out of memory").
var ( ErrUserLocked = Coded("ErrUserLocked", "user %s is locked: %s", CodeForbidden) ErrUserNotFound = Coded("ErrUserNotFound", "user %s not found: %s", CodeNotFound) ErrUserPermission = Coded("ErrUserPermission", "user %s lacks permission: %s", CodeForbidden) ErrUserSuspended = Coded("ErrUserSuspended", "user %s is suspended: %s", CodeForbidden) )
User Errors (Templated) Example: ErrUserNotFound("user123", "not in database").
var ( ErrInvalidFormat = Coded("ErrInvalidFormat", "invalid format: %s", CodeBadRequest) ErrValidationFailed = Coded("ErrValidationFailed", "validation failed: %s", CodeBadRequest) )
Validation Errors (Templated) Example: ErrValidationFailed("email", "invalid email format").
var ( ErrConflict = Coded("ErrConflict", "conflict occurred: %s", CodeConflict) ErrMethodNotAllowed = Coded("ErrMethodNotAllowed", "method %s not allowed", CodeMethodNotAllowed) ErrNotImplemented = Coded("ErrNotImplemented", "%s not implemented", CodeNotImplemented) ErrRateLimitExceeded = Coded("ErrRateLimitExceeded", "rate limit exceeded: %s", CodeTooManyRequests) ErrUnprocessable = Coded("ErrUnprocessable", "unprocessable entity: %s", CodeUnprocessable) )
Additional REST API Errors (Templated) Example: ErrMethodNotAllowed("POST", "only GET allowed").
var ( ErrDeserialization = Define("ErrDeserialization", "deserialization error: %s") ErrExternalService = Define("ErrExternalService", "external service (%s) error") ErrSerialization = Define("ErrSerialization", "serialization error: %s") ErrUnsupportedOperation = Coded("ErrUnsupportedOperation", "unsupported operation %s", CodeNotImplemented) )
Additional Domain-Specific Errors (Templated) Example: ErrSerialization("json", "invalid data").
var ( AuthFailed = Categorized(CategoryAuth, "AuthFailed", "authentication failed for %s: %s") BusinessError = Categorized(CategoryBusiness, "BusinessError", "business error: %s") DBError = Categorized(CategoryDatabase, "DBError", "database error: %s") IOError = Categorized(CategoryIO, "IOError", "I/O error: %s") NetworkError = Categorized(CategoryNetwork, "NetworkError", "network failure: %s") SystemError = Categorized(CategorySystem, "SystemError", "system error: %s") UserError = Categorized(CategoryUser, "UserError", "user error: %s") ValidationError = Categorized(CategoryValidation, "ValidationError", "validation error: %s") )
Predefined Templates with Categories (Templated) These are convenience wrappers with categories applied; use like AuthFailed("user", "reason").
Functions ¶
func Categorized ¶
func Categorized(category errors.ErrorCategory, name, template string) func(...interface{}) *errors.Error
Categorized creates a categorized error template and returns a function to create errors. The returned function applies the category to each error instance.
func CloseMonitor ¶
func CloseMonitor(name string)
CloseMonitor closes the alert channel for a specific error name. Thread-safe; subsequent alerts for this name are ignored.
func Coded ¶
Coded creates a templated error with a specific HTTP status code. It wraps Define and applies the code to each error instance returned.
func Configure ¶
func Configure(cfg Config)
Configure updates the global configuration for the errmgr package. Thread-safe; applies immediately to all subsequent operations.
func Copy ¶
Copy creates a new instance of a predefined static error, ensuring immutability of originals. Use this for static errors; templated errors should be called directly with arguments.
func Define ¶
Define creates a templated error that formats a message with provided arguments. The error is tracked in the registry if error management is enabled.
func GetThreshold ¶
GetThreshold returns the current threshold for an error name, if set. Returns 0 and false if no threshold is defined.
func Metrics ¶
Metrics returns a snapshot of error counts for monitoring systems. Returns nil if error management is disabled or no counts exist.
func RemoveThreshold ¶
func RemoveThreshold(name string)
RemoveThreshold removes the threshold for a specific error name. Thread-safe; no effect if no threshold exists.
func Reset ¶
func Reset()
Reset clears all counters and removes their registrations. Has no effect if error management is disabled.
func ResetCounter ¶
func ResetCounter(name string)
ResetCounter resets the occurrence counter for a specific error type. Has no effect if error management is disabled or the name isn’t registered.
func SetThreshold ¶
SetThreshold sets a count threshold for an error name, triggering alerts when exceeded. Alerts are sent to the Monitor channel if one exists for the name.
Types ¶
type Config ¶
type Config struct {
DisableMetrics bool // Disables counting and tracking if true
}
Config holds configuration for the errmgr package.
type Monitor ¶
type Monitor struct {
// contains filtered or unexported fields
}
Monitor represents an error monitoring channel for a specific error name. It receives alerts when the error count exceeds a configured threshold set via SetThreshold.
func NewMonitor ¶
NewMonitor creates a new Monitor for the given error name with a default buffer of 10. Reuses an existing channel if one is already registered; thread-safe. Use NewMonitorBuffered for a custom buffer size.
func NewMonitorBuffered ¶
NewMonitorBuffered creates a new Monitor for the given error name with a specified buffer size. Reuses an existing channel if one is already registered; thread-safe. Buffer must be non-negative (0 means unbuffered); use NewMonitor for the default buffer of 10.
func (*Monitor) Alerts ¶
Alerts returns the channel for receiving error alerts. Alerts are sent when the error count exceeds the threshold set by SetThreshold. Returns nil if the monitor has been closed.