Documentation
¶
Overview ¶
Package errors provides error handling utilities for the servicelib package.
Package errors provides a comprehensive error handling system for applications.
This package implements a structured approach to error handling, offering:
- A hierarchy of error types for different domains (application, domain, infrastructure)
- Error codes with HTTP status mapping
- Contextual information for debugging
- Stack traces for error origin tracking
- Utilities for creating, wrapping, and serializing errors
- Error type checking and categorization
The error types are organized into several categories:
- Domain errors: Represent business rule violations and domain-specific issues
- Infrastructure errors: Represent issues with external systems and resources
- Application errors: Represent issues with the application itself
Each error type provides specific contextual information relevant to its category, making it easier to understand, log, and respond to errors appropriately.
Example usage:
// Create a validation error err := errors.NewValidationError("Invalid email format", "email", nil) // Check error type if errors.IsValidationError(err) { // Handle validation error } // Create a database error dbErr := errors.NewDatabaseError("Failed to insert record", "INSERT", "users", err) // Get HTTP status code for error statusCode := errors.GetHTTPStatus(dbErr)
Package errors provides a comprehensive error handling system for the application. It includes error codes, HTTP status mapping, contextual information, and utilities for creating, wrapping, and serializing errors.
Index ¶
- Constants
- Variables
- func As(err error, target interface{}) bool
- func DetectErrorFromContext(ctx context.Context) error
- func DetectErrorType(err error) string
- func FormatErrorWithSource(err error, source string) string
- func GetHTTPStatus(err error) int
- func Is(err, target error) bool
- func IsApplicationError(err error) bool
- func IsAuthenticationError(err error) bool
- func IsAuthorizationError(err error) bool
- func IsBusinessRuleError(err error) bool
- func IsCancelled(err error) bool
- func IsConfigurationError(err error) bool
- func IsContextError(err error) bool
- func IsDatabaseError(err error) bool
- func IsDomainError(err error) bool
- func IsExternalServiceError(err error) bool
- func IsInfrastructureError(err error) bool
- func IsNetworkError(err error) bool
- func IsNotFoundError(err error) bool
- func IsRetryError(err error) bool
- func IsTimeout(err error) bool
- func IsTransientError(err error) bool
- func IsValidationError(err error) bool
- func New(code ErrorCode, message string) error
- func ToJSON(err error) string
- func Unwrap(err error) error
- func Wrap(err error, code ErrorCode, message string) error
- func WrapWithDetails(err error, code ErrorCode, message string, details map[string]interface{}) error
- func WrapWithOperation(err error, code ErrorCode, message string, operation string) error
- type ApplicationError
- type AuthenticationError
- type AuthorizationError
- type BaseError
- type BusinessRuleError
- type ConfigurationError
- type ContextError
- type DatabaseError
- type DomainError
- type ErrorCode
- type ExternalServiceError
- type InfrastructureError
- type NetworkError
- type NotFoundError
- type RetryError
- type ValidationError
- type ValidationErrors
Constants ¶
const ( // NotFoundCode indicates that a requested resource could not be found. NotFoundCode = core.NotFoundCode // InvalidInputCode indicates that the provided input is invalid. InvalidInputCode = core.InvalidInputCode // DatabaseErrorCode indicates an error occurred during a database operation. DatabaseErrorCode = core.DatabaseErrorCode // InternalErrorCode indicates an unexpected internal error. InternalErrorCode = core.InternalErrorCode // TimeoutCode indicates that an operation timed out. TimeoutCode = core.TimeoutCode // CanceledCode indicates that an operation was canceled. CanceledCode = core.CanceledCode // AlreadyExistsCode indicates that a resource already exists. AlreadyExistsCode = core.AlreadyExistsCode UnauthorizedCode = core.UnauthorizedCode // ForbiddenCode indicates that the authenticated user does not have permission. ForbiddenCode = core.ForbiddenCode // ValidationErrorCode indicates that input validation failed. ValidationErrorCode = core.ValidationErrorCode // BusinessRuleViolationCode indicates that a business rule was violated. BusinessRuleViolationCode = core.BusinessRuleViolationCode // ExternalServiceErrorCode indicates an error occurred in an external service. ExternalServiceErrorCode = core.ExternalServiceErrorCode // NetworkErrorCode indicates a network-related error. NetworkErrorCode = core.NetworkErrorCode // ConfigurationErrorCode indicates an error in the application configuration. ConfigurationErrorCode = core.ConfigurationErrorCode // ResourceExhaustedCode indicates that a resource limit has been reached. ResourceExhaustedCode = core.ResourceExhaustedCode // DataCorruptionCode indicates that data is corrupted or invalid. DataCorruptionCode = core.DataCorruptionCode // ConcurrencyErrorCode indicates a concurrency-related error. ConcurrencyErrorCode = core.ConcurrencyErrorCode )
Error code constants define the standard error categories used throughout the application.
Variables ¶
var ( // ErrNotFound represents a generic "resource not found" error. ErrNotFound = core.NewBaseError(NotFoundCode, "resource not found", nil) // ErrInvalidInput represents a generic "invalid input" error. ErrInvalidInput = core.NewBaseError(InvalidInputCode, "invalid input", nil) // ErrInternal represents a generic "internal error" for unexpected system issues. ErrInternal = core.NewBaseError(InternalErrorCode, "internal error", nil) ErrUnauthorized = core.NewBaseError(UnauthorizedCode, "unauthorized", nil) // ErrForbidden represents a generic "forbidden" error for authorization failures. ErrForbidden = core.NewBaseError(ForbiddenCode, "forbidden", nil) // ErrTimeout represents a generic "operation timed out" error. ErrTimeout = core.NewBaseError(TimeoutCode, "operation timed out", nil) // ErrCanceled represents a generic "operation canceled" error. ErrCanceled = core.NewBaseError(CanceledCode, "operation canceled", nil) // ErrAlreadyExists represents a generic "resource already exists" error. ErrAlreadyExists = core.NewBaseError(AlreadyExistsCode, "resource already exists", nil) )
Standard errors provides commonly used error instances that can be used directly or wrapped.
Functions ¶
func As ¶
As finds the first error in err's chain that matches the type of target, and if so, sets target to that error value and returns true. This is a wrapper around the standard errors.As function.
Parameters:
- err: The error to check.
- target: A pointer to a variable of the error type to check for.
Returns:
- true if an error of the target type was found in err's chain, false otherwise.
func DetectErrorFromContext ¶ added in v1.5.0
DetectErrorFromContext extracts an error from a context if present
func DetectErrorType ¶ added in v1.5.0
DetectErrorType returns a string describing the type of error
func FormatErrorWithSource ¶ added in v1.5.0
FormatErrorWithSource formats an error with its source information
func GetHTTPStatus ¶
GetHTTPStatus returns the HTTP status code for an error. This function maps error codes to appropriate HTTP status codes. If the error is nil, it returns 0.
Parameters:
- err: The error to get the HTTP status code for.
Returns:
- The HTTP status code corresponding to the error, or 0 if the error is nil or has no mapping.
func Is ¶
Is reports whether any error in err's chain matches target. This is a wrapper around the standard errors.Is function.
Parameters:
- err: The error to check.
- target: The target error to compare against.
Returns:
- true if err or any error in its chain matches target, false otherwise.
func IsApplicationError ¶
IsApplicationError checks if an error is an application error. Application errors include ApplicationError, ConfigurationError, AuthenticationError, and AuthorizationError.
Parameters:
- err: The error to check.
Returns:
- true if the error is an application error, false otherwise.
func IsAuthenticationError ¶ added in v1.4.0
IsAuthenticationError checks if an error is an AuthenticationError. Use this to determine if an error is related to authentication failure.
Parameters:
- err: The error to check.
Returns:
- true if the error is an AuthenticationError, false otherwise.
func IsAuthorizationError ¶ added in v1.4.0
IsAuthorizationError checks if an error is an AuthorizationError. Use this to determine if an error is related to authorization failure.
Parameters:
- err: The error to check.
Returns:
- true if the error is an AuthorizationError, false otherwise.
func IsBusinessRuleError ¶ added in v1.4.0
IsBusinessRuleError checks if an error is a BusinessRuleError. Use this to determine if an error is related to a business rule violation.
Parameters:
- err: The error to check.
Returns:
- true if the error is a BusinessRuleError, false otherwise.
func IsCancelled ¶
IsCancelled checks if an error is a cancellation error. This function checks for errors that indicate an operation was canceled.
Parameters:
- err: The error to check.
Returns:
- true if the error indicates cancellation, false otherwise.
func IsConfigurationError ¶ added in v1.4.0
IsConfigurationError checks if an error is a ConfigurationError. Use this to determine if an error is related to invalid or missing configuration.
Parameters:
- err: The error to check.
Returns:
- true if the error is a ConfigurationError, false otherwise.
func IsContextError ¶ added in v1.5.0
IsContextError checks if an error is a ContextError. Use this to determine if an error is related to context cancellation or timeout.
Parameters:
- err: The error to check.
Returns:
- true if the error is a ContextError, false otherwise.
func IsDatabaseError ¶ added in v1.4.0
IsDatabaseError checks if an error is a DatabaseError. Use this to determine if an error is related to a database operation.
Parameters:
- err: The error to check.
Returns:
- true if the error is a DatabaseError, false otherwise.
func IsDomainError ¶ added in v1.4.0
IsDomainError checks if an error is a domain error. Domain errors include DomainError, ValidationError, BusinessRuleError, and NotFoundError.
Parameters:
- err: The error to check.
Returns:
- true if the error is a domain error, false otherwise.
func IsExternalServiceError ¶ added in v1.4.0
IsExternalServiceError checks if an error is an ExternalServiceError. Use this to determine if an error is related to an external service call.
Parameters:
- err: The error to check.
Returns:
- true if the error is an ExternalServiceError, false otherwise.
func IsInfrastructureError ¶ added in v1.4.0
IsInfrastructureError checks if an error is an infrastructure error. Infrastructure errors include InfrastructureError, DatabaseError, NetworkError, and ExternalServiceError.
Parameters:
- err: The error to check.
Returns:
- true if the error is an infrastructure error, false otherwise.
func IsNetworkError ¶ added in v1.4.0
IsNetworkError checks if an error is a network-related error. This function checks for NetworkError types from this package, as well as errors that implement the net.Error interface, timeout errors, and errors with common network error messages.
Parameters:
- err: The error to check.
Returns:
- true if the error is a network-related error, false otherwise.
func IsNotFoundError ¶
IsNotFoundError checks if an error is a NotFoundError. Use this to determine if an error is related to a resource not being found.
Parameters:
- err: The error to check.
Returns:
- true if the error is a NotFoundError, false otherwise.
func IsRetryError ¶ added in v1.5.0
IsRetryError checks if an error is a RetryError. Use this to determine if an error occurred after exhausting all retry attempts.
Parameters:
- err: The error to check.
Returns:
- true if the error is a RetryError, false otherwise.
func IsTimeout ¶
IsTimeout checks if an error is a timeout error. This function checks for errors that indicate an operation timed out. It checks for timeout errors from this package, context deadline exceeded errors, errors that implement the net.Error interface with a Timeout method, and errors with common timeout error messages.
Parameters:
- err: The error to check.
Returns:
- true if the error indicates a timeout, false otherwise.
func IsTransientError ¶ added in v1.5.0
IsTransientError checks if an error is a transient error that may be resolved by retrying. Transient errors include network errors, timeout errors, and errors that explicitly indicate they are temporary. This function is useful for determining if an operation should be retried.
Parameters:
- err: The error to check.
Returns:
- true if the error is likely transient and may be resolved by retrying, false otherwise.
func IsValidationError ¶
IsValidationError checks if an error is a ValidationError. Use this to determine if an error is related to input validation.
Parameters:
- err: The error to check.
Returns:
- true if the error is a ValidationError, false otherwise.
func New ¶
New creates a new BaseError with the specified error code and message.
Parameters:
- code: The error code that categorizes this error.
- message: A human-readable description of the error.
Returns:
- An error instance with the specified code and message.
func ToJSON ¶
ToJSON converts an error to a JSON string representation. This is useful for logging errors or returning them in API responses.
Parameters:
- err: The error to convert to JSON.
Returns:
- A JSON string representation of the error.
func Unwrap ¶
Unwrap returns the underlying error of err, if any. This is a wrapper around the standard errors.Unwrap function.
Parameters:
- err: The error to unwrap.
Returns:
- The underlying error of err, or nil if err has no underlying error.
func Wrap ¶
Wrap wraps an existing error with additional context, including an error code and message. If the input error is nil, it returns nil.
Parameters:
- err: The original error to wrap.
- code: The error code to assign to the wrapped error.
- message: A human-readable description of the error context.
Returns:
- A new error that wraps the original error with additional context.
func WrapWithDetails ¶ added in v1.4.0
func WrapWithDetails(err error, code ErrorCode, message string, details map[string]interface{}) error
WrapWithDetails wraps an error with additional context, including a map of details. This is useful for providing structured data about the error context. If the input error is nil, it returns nil.
Parameters:
- err: The original error to wrap.
- code: The error code to assign to the wrapped error.
- message: A human-readable description of the error context.
- details: A map of key-value pairs providing additional context.
Returns:
- A new error that wraps the original error with additional context.
func WrapWithOperation ¶
WrapWithOperation wraps an error with additional context, including an operation name. This is useful for providing context about what operation was being performed when the error occurred. If the input error is nil, it returns nil.
Parameters:
- err: The original error to wrap.
- code: The error code to assign to the wrapped error.
- message: A human-readable description of the error context.
- operation: The name of the operation that was being performed.
Returns:
- A new error that wraps the original error with additional context.
Types ¶
type ApplicationError ¶
type ApplicationError = app.ApplicationError
ApplicationError represents errors that occur in the application layer. Use this for errors related to application logic and configuration.
func NewApplicationError ¶
func NewApplicationError(code ErrorCode, message string, cause error) *ApplicationError
NewApplicationError creates a new ApplicationError with the specified error code, message, and cause. Use this for errors that occur in the application layer.
Parameters:
- code: The error code that categorizes this error.
- message: A human-readable description of the error.
- cause: The underlying error that caused this error, if any.
Returns:
- A new ApplicationError instance.
type AuthenticationError ¶ added in v1.4.0
type AuthenticationError = app.AuthenticationError
AuthenticationError represents an error that occurs during authentication. It includes the username that failed authentication.
func NewAuthenticationError ¶ added in v1.4.0
func NewAuthenticationError(message string, username string, cause error) *AuthenticationError
NewAuthenticationError creates a new AuthenticationError for a specific user. Use this when authentication fails for a user.
Parameters:
- message: A human-readable description of the authentication error.
- username: The username of the user who failed authentication.
- cause: The underlying error that caused this error, if any.
Returns:
- A new AuthenticationError instance.
type AuthorizationError ¶ added in v1.4.0
type AuthorizationError = app.AuthorizationError
AuthorizationError represents an error that occurs during authorization. It includes the username, resource, and action that failed authorization.
func NewAuthorizationError ¶ added in v1.4.0
func NewAuthorizationError(message string, username string, resource string, action string, cause error) *AuthorizationError
NewAuthorizationError creates a new AuthorizationError for a specific user, resource, and action. Use this when a user is not authorized to perform an action on a resource.
Parameters:
- message: A human-readable description of the authorization error.
- username: The username of the user who is not authorized.
- resource: The resource the user is trying to access.
- action: The action the user is trying to perform.
- cause: The underlying error that caused this error, if any.
Returns:
- A new AuthorizationError instance.
type BaseError ¶ added in v1.4.0
BaseError is the foundation error type that all other error types extend. It provides common functionality like error codes, messages, and cause tracking.
type BusinessRuleError ¶ added in v1.4.0
type BusinessRuleError = domain.BusinessRuleError
BusinessRuleError represents an error that occurs when a business rule is violated. It includes the name of the rule that was violated.
func NewBusinessRuleError ¶ added in v1.4.0
func NewBusinessRuleError(message string, rule string, cause error) *BusinessRuleError
NewBusinessRuleError creates a new BusinessRuleError for a specific business rule. Use this when a business rule is violated.
Parameters:
- message: A human-readable description of the business rule violation.
- rule: The name of the business rule that was violated.
- cause: The underlying error that caused this error, if any.
Returns:
- A new BusinessRuleError instance.
type ConfigurationError ¶ added in v1.4.0
type ConfigurationError = app.ConfigurationError
ConfigurationError represents an error that occurs due to invalid configuration. It includes the configuration key and value that caused the error.
func NewConfigurationError ¶ added in v1.4.0
func NewConfigurationError(message string, configKey string, configValue string, cause error) *ConfigurationError
NewConfigurationError creates a new ConfigurationError for a specific configuration key. Use this when an error occurs due to invalid or missing configuration.
Parameters:
- message: A human-readable description of the configuration error.
- configKey: The configuration key that caused the error.
- configValue: The value of the configuration key that caused the error.
- cause: The underlying error that caused this error, if any.
Returns:
- A new ConfigurationError instance.
type ContextError ¶ added in v1.5.0
type ContextError = infra.ContextError
ContextError represents an error that occurs due to context cancellation or timeout. Use this when an operation fails because its context was canceled or timed out.
func NewContextError ¶ added in v1.5.0
func NewContextError(message string, cause error) *ContextError
NewContextError creates a new ContextError when an operation fails due to context cancellation or timeout. Use this when an operation fails because its context was canceled or timed out.
Parameters:
- message: A human-readable description of the context error.
- cause: The underlying error that caused this error, if any.
Returns:
- A new ContextError instance.
type DatabaseError ¶ added in v1.4.0
type DatabaseError = infra.DatabaseError
DatabaseError represents an error that occurs during a database operation. It includes the operation and table name where the error occurred.
func NewDatabaseError ¶ added in v1.4.0
func NewDatabaseError(message string, operation string, table string, cause error) *DatabaseError
NewDatabaseError creates a new DatabaseError for a specific database operation. Use this when a database operation fails.
Parameters:
- message: A human-readable description of the database error.
- operation: The database operation that failed (e.g., "SELECT", "INSERT").
- table: The name of the database table involved in the operation.
- cause: The underlying error that caused this error, if any.
Returns:
- A new DatabaseError instance.
type DomainError ¶
type DomainError = domain.DomainError
DomainError represents errors that occur due to domain logic violations. Use this for errors related to business rules and domain constraints.
func NewDomainError ¶
func NewDomainError(code ErrorCode, message string, cause error) *DomainError
NewDomainError creates a new DomainError with the specified error code, message, and cause. Use this for errors that occur due to domain logic violations.
Parameters:
- code: The error code that categorizes this error.
- message: A human-readable description of the error.
- cause: The underlying error that caused this error, if any.
Returns:
- A new DomainError instance.
type ErrorCode ¶
ErrorCode is an alias for core.ErrorCode that represents a categorized error type. It is used to classify errors and map them to appropriate HTTP status codes.
type ExternalServiceError ¶ added in v1.4.0
type ExternalServiceError = infra.ExternalServiceError
ExternalServiceError represents an error that occurs when calling an external service. It includes the service name and endpoint where the error occurred.
func NewExternalServiceError ¶ added in v1.4.0
func NewExternalServiceError(message string, serviceName string, endpoint string, cause error) *ExternalServiceError
NewExternalServiceError creates a new ExternalServiceError for a specific external service call. Use this when a call to an external service fails.
Parameters:
- message: A human-readable description of the external service error.
- serviceName: The name of the external service.
- endpoint: The specific endpoint or API that was called.
- cause: The underlying error that caused this error, if any.
Returns:
- A new ExternalServiceError instance.
type InfrastructureError ¶ added in v1.4.0
type InfrastructureError = infra.InfrastructureError
InfrastructureError represents errors that occur in the infrastructure layer. Use this for errors related to external systems, databases, networks, etc.
func NewInfrastructureError ¶ added in v1.4.0
func NewInfrastructureError(code ErrorCode, message string, cause error) *InfrastructureError
NewInfrastructureError creates a new InfrastructureError with the specified error code, message, and cause. Use this for errors that occur in the infrastructure layer.
Parameters:
- code: The error code that categorizes this error.
- message: A human-readable description of the error.
- cause: The underlying error that caused this error, if any.
Returns:
- A new InfrastructureError instance.
type NetworkError ¶ added in v1.4.0
type NetworkError = infra.NetworkError
NetworkError represents an error that occurs during network communication. It includes the host and port where the error occurred.
func NewNetworkError ¶ added in v1.4.0
func NewNetworkError(message string, host string, port string, cause error) *NetworkError
NewNetworkError creates a new NetworkError for a specific network connection. Use this when a network operation fails.
Parameters:
- message: A human-readable description of the network error.
- host: The hostname or IP address of the remote host.
- port: The port number of the remote host.
- cause: The underlying error that caused this error, if any.
Returns:
- A new NetworkError instance.
type NotFoundError ¶
type NotFoundError = domain.NotFoundError
NotFoundError represents an error that occurs when a requested resource cannot be found. It includes the resource type and ID that was not found.
func NewNotFoundError ¶
func NewNotFoundError(resourceType string, resourceID string, cause error) *NotFoundError
NewNotFoundError creates a new NotFoundError for a specific resource. Use this when a requested resource cannot be found.
Parameters:
- resourceType: The type of resource that was not found (e.g., "user", "product").
- resourceID: The identifier of the resource that was not found.
- cause: The underlying error that caused this error, if any.
Returns:
- A new NotFoundError instance.
type RetryError ¶ added in v1.5.0
type RetryError = infra.RetryError
RetryError represents an error that occurs when all retry attempts have been exhausted. It includes the number of attempts made and the maximum allowed attempts.
func NewRetryError ¶ added in v1.5.0
func NewRetryError(message string, cause error, attempts int, maxAttempts int) *RetryError
NewRetryError creates a new RetryError when all retry attempts have been exhausted. Use this when an operation fails after multiple retry attempts.
Parameters:
- message: A human-readable description of the retry error.
- cause: The underlying error that caused the retries to fail.
- attempts: The number of attempts that were made.
- maxAttempts: The maximum number of attempts that were allowed.
Returns:
- A new RetryError instance.
type ValidationError ¶
type ValidationError = domain.ValidationError
ValidationError represents an error that occurs when input validation fails. It includes the field name that failed validation.
func NewValidationError ¶
func NewValidationError(message string, field string, cause error) *ValidationError
NewValidationError creates a new ValidationError for a specific field. Use this when input validation fails for a specific field.
Parameters:
- message: A human-readable description of the validation error.
- field: The name of the field that failed validation.
- cause: The underlying error that caused this error, if any.
Returns:
- A new ValidationError instance.
type ValidationErrors ¶
type ValidationErrors = domain.ValidationErrors
ValidationErrors represents a collection of ValidationError instances. Use this when multiple validation errors occur simultaneously.
func NewValidationErrors ¶
func NewValidationErrors(message string, errors ...*ValidationError) *ValidationErrors
NewValidationErrors creates a new ValidationErrors collection with the specified errors. Use this when multiple validation errors occur simultaneously.
Parameters:
- message: A human-readable description of the validation errors.
- errors: A list of ValidationError instances to include in the collection.
Returns:
- A new ValidationErrors instance containing all the specified validation errors.
Directories
¶
Path | Synopsis |
---|---|
Package app provides application-level error types for the application.
|
Package app provides application-level error types for the application. |
Package core provides the core error handling functionality for the application.
|
Package core provides the core error handling functionality for the application. |
Package domain provides domain-specific error types for the application.
|
Package domain provides domain-specific error types for the application. |
Package http provides HTTP-related error utilities for the application.
|
Package http provides HTTP-related error utilities for the application. |
Package infra provides infrastructure-related error types for the application.
|
Package infra provides infrastructure-related error types for the application. |
Package log provides logging integration for the error handling system.
|
Package log provides logging integration for the error handling system. |
Package metrics provides metrics integration for the error handling system.
|
Package metrics provides metrics integration for the error handling system. |
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
Package trace provides tracing integration for the error handling system.
|
Package trace provides tracing integration for the error handling system. |
Package types provides specific error types for the errors package.
|
Package types provides specific error types for the errors package. |