Documentation
¶
Overview ¶
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.
Package errors provides generic error interfaces and implementations that can be used across different applications.
Index ¶
- Variables
- func AlreadyExists(format string, args ...interface{}) error
- func As(err error, target interface{}) bool
- func BusinessRuleViolation(format string, args ...interface{}) error
- func Canceled(format string, args ...interface{}) error
- func Concurrency(format string, args ...interface{}) error
- func Configuration(format string, args ...interface{}) error
- func DataCorruption(format string, args ...interface{}) error
- func DatabaseOperation(err error, format string, args ...interface{}) error
- func ExternalService(err error, service string, format string, args ...interface{}) error
- func Forbidden(format string, args ...interface{}) error
- func GetHTTPStatus(err error) int
- func GetHTTPStatusFromError(err error) int
- func Internal(err error, format string, args ...interface{}) error
- func InvalidInput(format string, args ...interface{}) error
- func Is(err error, target error) bool
- func IsApplicationError(err error) bool
- func IsCancelled(err error) bool
- func IsConflict(err error) bool
- func IsForbidden(err error) bool
- func IsInternal(err error) bool
- func IsInvalidInput(err error) bool
- func IsNotFound(err error) bool
- func IsNotFoundError(err error) bool
- func IsRepositoryError(err error) bool
- func IsTimeout(err error) bool
- func IsUnauthorized(err error) bool
- func IsValidationError(err error) bool
- func Network(err error, format string, args ...interface{}) error
- func New(op, code, message string, original error) error
- func NotFound(format string, args ...interface{}) error
- func ResourceExhausted(format string, args ...interface{}) error
- func Timeout(format string, args ...interface{}) error
- func ToJSON(err error) string
- func Unauthorized(format string, args ...interface{}) error
- func Unwrap(err error) error
- func Validation(format string, args ...interface{}) error
- func WithDetails(err error, details map[string]interface{}) error
- func Wrap(err error, op, message string) error
- func WrapWithOperation(err error, operation string, format string, args ...interface{}) error
- type AppError
- type ApplicationError
- type ApplicationErrorInterface
- type ContextualError
- type DomainError
- type DomainErrorType
- type Error
- type ErrorCode
- type ErrorContext
- type ErrorWithCode
- type ErrorWithHTTPStatus
- type GenericError
- type NotFoundError
- type NotFoundErrorInterface
- type RepositoryError
- type RepositoryErrorInterface
- type ValidationError
- type ValidationErrorInterface
- type ValidationErrors
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound is returned when a requested resource is not found ErrNotFound = errors.New("resource not found") // ErrAlreadyExists is returned when a resource already exists ErrAlreadyExists = errors.New("resource already exists") // ErrInvalidInput is returned when the input to a function is invalid ErrInvalidInput = errors.New("invalid input") // ErrInternal is returned when an internal error occurs ErrInternal = errors.New("internal error") ErrUnauthorized = errors.New("unauthorized") // ErrForbidden is returned when a user is forbidden from performing an action ErrForbidden = errors.New("forbidden") // ErrTimeout is returned when an operation times out ErrTimeout = errors.New("operation timed out") // ErrCancelled is returned when an operation is cancelled ErrCancelled = errors.New("operation cancelled") // ErrConflict is returned when there is a conflict with the current state ErrConflict = errors.New("conflict with current state") )
Standard errors that can be used throughout the application
Functions ¶
func AlreadyExists ¶
AlreadyExists creates a new error for when a resource already exists. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with AlreadyExistsCode and HTTP 409 status
func As ¶
As finds the first error in err's chain that matches target. This is a wrapper around errors.As that adds support for ContextualError. Parameters:
- err: The error to check
- target: A pointer to the error type to match against
Returns:
- bool: True if a match was found
func BusinessRuleViolation ¶
BusinessRuleViolation creates a new error for when a business rule is violated. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with BusinessRuleViolationCode and HTTP 422 status
func Canceled ¶
Canceled creates a new error for when an operation is canceled. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with CanceledCode and HTTP 408 status
func Concurrency ¶
Concurrency creates a new error for concurrency-related errors. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ConcurrencyErrorCode and HTTP 409 status
func Configuration ¶
Configuration creates a new error for configuration errors. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ConfigurationErrorCode and HTTP 500 status
func DataCorruption ¶
DataCorruption creates a new error for when data is corrupted. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with DataCorruptionCode and HTTP 500 status
func DatabaseOperation ¶
DatabaseOperation creates a new error for database operation failures. Parameters:
- err: The original error
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with DatabaseErrorCode and HTTP 500 status
func ExternalService ¶
ExternalService creates a new error for external service call failures. Parameters:
- err: The original error
- service: The name of the external service
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ExternalServiceErrorCode and HTTP 502 status
func Forbidden ¶
Forbidden creates a new error for authorization failures. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ForbiddenCode and HTTP 403 status
func GetHTTPStatus ¶
GetHTTPStatus returns the HTTP status code from an error. If the error is a ContextualError, it returns the HTTP status from the context. Otherwise, it returns 0. Parameters:
- err: The error to get the HTTP status from
Returns:
- int: The HTTP status code, or 0 if not available
func GetHTTPStatusFromError ¶
GetHTTPStatusFromError returns the HTTP status code for an error
func Internal ¶
Internal creates a new error for internal server errors. Parameters:
- err: The original error
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with InternalErrorCode and HTTP 500 status
func InvalidInput ¶
InvalidInput creates a new error for when input validation fails. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with InvalidInputCode and HTTP 400 status
func Is ¶
Is checks if an error matches a target error. This is a wrapper around errors.Is that adds support for ContextualError. Parameters:
- err: The error to check
- target: The target error to match against
Returns:
- bool: True if the error matches the target
func IsApplicationError ¶
IsApplicationError checks if an error is an application error
func IsCancelled ¶
IsCancelled returns true if the error is a cancelled error
func IsConflict ¶
IsConflict returns true if the error is a conflict error
func IsForbidden ¶
IsForbidden returns true if the error is a forbidden error
func IsInternal ¶
IsInternal returns true if the error is an internal error
func IsInvalidInput ¶
IsInvalidInput returns true if the error is an invalid input error
func IsNotFound ¶
IsNotFound returns true if the error is a not found error
func IsNotFoundError ¶
IsNotFoundError checks if an error is a not found error
func IsRepositoryError ¶
IsRepositoryError checks if an error is a repository error
func IsUnauthorized ¶
IsUnauthorized returns true if the error is an unauthorized error
func IsValidationError ¶
IsValidationError checks if an error is a validation error
func Network ¶
Network creates a new error for network-related errors. Parameters:
- err: The original error
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with NetworkErrorCode and HTTP 503 status
func NotFound ¶
NotFound creates a new error for when a resource is not found. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with NotFoundCode and HTTP 404 status
func ResourceExhausted ¶
ResourceExhausted creates a new error for when a resource limit is reached. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ResourceExhaustedCode and HTTP 429 status
func Timeout ¶
Timeout creates a new error for when an operation times out. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with TimeoutCode and HTTP 504 status
func ToJSON ¶
ToJSON converts an error to a JSON string. If the error is a ContextualError, it uses the MarshalJSON method. Otherwise, it creates a simple JSON object with the error message. Parameters:
- err: The error to convert to JSON
Returns:
- string: The JSON representation of the error
func Unauthorized ¶
Unauthorized creates a new error for authentication failures. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with UnauthorizedCode and HTTP 401 status
func Unwrap ¶
Unwrap returns the underlying error. This is a wrapper around errors.Unwrap that adds support for ContextualError. Parameters:
- err: The error to unwrap
Returns:
- error: The underlying error, or nil if there is none
func Validation ¶
Validation creates a new error for domain validation errors. Parameters:
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error with ValidationErrorCode and HTTP 400 status
func WithDetails ¶
WithDetails adds details to an error. It preserves the error chain and adds additional context information. Parameters:
- err: The error to enhance
- details: A map of additional details to add to the error
Returns:
- error: A new error with the added details
func WrapWithOperation ¶
WrapWithOperation wraps an error with an operation name and message. It preserves the error chain and adds source location information. Parameters:
- err: The error to wrap
- operation: The name of the operation that failed
- format: The error message format string
- args: Arguments for the format string
Returns:
- error: A new error that wraps the original error
Types ¶
type AppError ¶
AppError is a generic error type that can be used for different error categories
func NewAppError ¶
NewAppError creates a new AppError
type ApplicationError ¶
ApplicationError represents an error that occurred in the application layer
func NewApplicationError ¶
func NewApplicationError(err error, message, code string) *ApplicationError
NewApplicationError creates a new ApplicationError
func (*ApplicationError) Error ¶
func (e *ApplicationError) Error() string
func (*ApplicationError) Unwrap ¶
func (e *ApplicationError) Unwrap() error
type ApplicationErrorInterface ¶
type ApplicationErrorInterface interface {
ErrorWithCode
ErrorWithHTTPStatus
// IsApplicationError identifies this as an application error
IsApplicationError() bool
}
ApplicationErrorInterface is an interface for application errors
type ContextualError ¶
type ContextualError struct {
// Original is the original error that was wrapped
Original error
// Context contains additional information about the error
Context ErrorContext
}
ContextualError is an error with additional context. It wraps another error and adds contextual information like operation name, error code, HTTP status, and source location.
func (*ContextualError) Code ¶
func (e *ContextualError) Code() ErrorCode
Code returns the error code.
func (*ContextualError) Error ¶
func (e *ContextualError) Error() string
Error returns the error message with contextual information.
func (*ContextualError) HTTPStatus ¶
func (e *ContextualError) HTTPStatus() int
HTTPStatus returns the HTTP status code.
func (*ContextualError) MarshalJSON ¶
func (e *ContextualError) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface.
func (*ContextualError) Unwrap ¶
func (e *ContextualError) Unwrap() error
Unwrap returns the original error.
type DomainError ¶
type DomainError = AppError[DomainErrorType]
DomainError represents an error that occurred in the domain layer
func NewDomainError ¶
func NewDomainError(err error, message, code string) *DomainError
NewDomainError creates a new DomainError
type DomainErrorType ¶
type DomainErrorType string
DomainErrorType represents the type of domain error
const (
DomainErrorGeneral DomainErrorType = "DOMAIN_ERROR"
)
Domain error type constants
type Error ¶
type Error struct {
// Original is the original error
Original error
// Code is a machine-readable error code
Code string
// Message is a human-readable error message
Message string
// Op is the operation that caused the error
Op string
// Param is the parameter that caused the error
Param string
}
Error represents a domain error with operation context
type ErrorCode ¶
type ErrorCode string
ErrorCode represents a unique error code for categorizing errors. These codes are used for error identification, logging, and mapping to HTTP status codes.
const ( // NotFoundCode is used when a resource is not found. // Maps to HTTP 404 Not Found. NotFoundCode ErrorCode = "NOT_FOUND" // InvalidInputCode is used when input validation fails. // Maps to HTTP 400 Bad Request. InvalidInputCode ErrorCode = "INVALID_INPUT" // DatabaseErrorCode is used for database operation failures. // Maps to HTTP 500 Internal Server Error. DatabaseErrorCode ErrorCode = "DATABASE_ERROR" // InternalErrorCode is used for internal server errors. // Maps to HTTP 500 Internal Server Error. InternalErrorCode ErrorCode = "INTERNAL_ERROR" // TimeoutCode is used when an operation times out. // Maps to HTTP 504 Gateway Timeout. TimeoutCode ErrorCode = "TIMEOUT" // CanceledCode is used when an operation is canceled. // Maps to HTTP 408 Request Timeout. CanceledCode ErrorCode = "CANCELED" // AlreadyExistsCode is used when a resource already exists. // Maps to HTTP 409 Conflict. AlreadyExistsCode ErrorCode = "ALREADY_EXISTS" // Maps to HTTP 401 Unauthorized. UnauthorizedCode ErrorCode = "UNAUTHORIZED" // ForbiddenCode is used for authorization failures. // Maps to HTTP 403 Forbidden. ForbiddenCode ErrorCode = "FORBIDDEN" // ValidationErrorCode is used for domain validation errors. // Maps to HTTP 400 Bad Request. ValidationErrorCode ErrorCode = "VALIDATION_ERROR" // BusinessRuleViolationCode is used when a business rule is violated. // Maps to HTTP 422 Unprocessable Entity. BusinessRuleViolationCode ErrorCode = "BUSINESS_RULE_VIOLATION" // ExternalServiceErrorCode is used when an external service call fails. // Maps to HTTP 502 Bad Gateway. ExternalServiceErrorCode ErrorCode = "EXTERNAL_SERVICE_ERROR" // NetworkErrorCode is used for network-related errors. // Maps to HTTP 503 Service Unavailable. NetworkErrorCode ErrorCode = "NETWORK_ERROR" // ConfigurationErrorCode is used for configuration errors. // Maps to HTTP 500 Internal Server Error. ConfigurationErrorCode ErrorCode = "CONFIGURATION_ERROR" // ResourceExhaustedCode is used when a resource limit is reached. // Maps to HTTP 429 Too Many Requests. ResourceExhaustedCode ErrorCode = "RESOURCE_EXHAUSTED" // DataCorruptionCode is used when data is corrupted. // Maps to HTTP 500 Internal Server Error. DataCorruptionCode ErrorCode = "DATA_CORRUPTION" // ConcurrencyErrorCode is used for concurrency-related errors. // Maps to HTTP 409 Conflict. ConcurrencyErrorCode ErrorCode = "CONCURRENCY_ERROR" )
Standard error codes define all possible error categories in the application.
type ErrorContext ¶
type ErrorContext struct {
// Operation is the name of the operation that failed
Operation string `json:"operation,omitempty"`
// Source is the file and line where the error occurred
Source string `json:"source,omitempty"`
// Line is the line number where the error occurred
Line int `json:"line,omitempty"`
// Code is the error code
Code ErrorCode `json:"code,omitempty"`
// HTTPStatus is the HTTP status code to return for this error
HTTPStatus int `json:"http_status,omitempty"`
// Details contains additional information about the error
Details map[string]interface{} `json:"details,omitempty"`
}
ErrorContext holds additional context for an error. It includes information about the operation that failed, the source location, and any additional details that might be useful for debugging or error reporting.
type ErrorWithCode ¶
ErrorWithCode is an interface for errors that have an error code
type ErrorWithHTTPStatus ¶
type ErrorWithHTTPStatus interface {
error
// HTTPStatus returns the HTTP status code
HTTPStatus() int
}
ErrorWithHTTPStatus is an interface for errors that have an HTTP status code
type GenericError ¶
GenericError is a generic error type that can be used for different error categories
func NewGenericError ¶
func NewGenericError[T any](err error, message, code string, category T) *GenericError[T]
NewGenericError creates a new GenericError
func (*GenericError[T]) Error ¶
func (e *GenericError[T]) Error() string
func (*GenericError[T]) Unwrap ¶
func (e *GenericError[T]) Unwrap() error
type NotFoundError ¶
NotFoundError represents a resource not found error
func NewNotFoundError ¶
func NewNotFoundError(resourceType, id string) *NotFoundError
NewNotFoundError creates a new NotFoundError
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Is ¶
func (e *NotFoundError) Is(target error) bool
Is implements the errors.Is interface for NotFoundError
type NotFoundErrorInterface ¶
type NotFoundErrorInterface interface {
ErrorWithCode
ErrorWithHTTPStatus
// IsNotFoundError identifies this as a not found error
IsNotFoundError() bool
}
NotFoundErrorInterface is an interface for not found errors
type RepositoryError ¶
RepositoryError represents an error that occurred in the repository layer
func NewRepositoryError ¶
func NewRepositoryError(err error, message, code string) *RepositoryError
NewRepositoryError creates a new RepositoryError
func (*RepositoryError) Error ¶
func (e *RepositoryError) Error() string
func (*RepositoryError) Unwrap ¶
func (e *RepositoryError) Unwrap() error
type RepositoryErrorInterface ¶
type RepositoryErrorInterface interface {
ErrorWithCode
ErrorWithHTTPStatus
// IsRepositoryError identifies this as a repository error
IsRepositoryError() bool
}
RepositoryErrorInterface is an interface for repository errors
type ValidationError ¶
ValidationError represents a validation error
func NewFieldValidationError ¶
func NewFieldValidationError(msg, field string) *ValidationError
NewFieldValidationError creates a new ValidationError with a field name
func NewValidationError ¶
func NewValidationError(msg string) *ValidationError
NewValidationError creates a new ValidationError
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationErrorInterface ¶
type ValidationErrorInterface interface {
ErrorWithCode
ErrorWithHTTPStatus
// IsValidationError identifies this as a validation error
IsValidationError() bool
}
ValidationErrorInterface is an interface for validation errors
type ValidationErrors ¶
type ValidationErrors struct {
Errors []*ValidationError
}
ValidationErrors represents multiple validation errors
func NewValidationErrors ¶
func NewValidationErrors(errors ...*ValidationError) *ValidationErrors
NewValidationErrors creates a new ValidationErrors
func (*ValidationErrors) AddError ¶
func (e *ValidationErrors) AddError(err *ValidationError)
AddError adds a validation error to the collection
func (*ValidationErrors) Error ¶
func (e *ValidationErrors) Error() string
func (*ValidationErrors) HasErrors ¶
func (e *ValidationErrors) HasErrors() bool
HasErrors returns true if there are any validation errors
Directories
¶
| Path | Synopsis |
|---|---|
|
Package core provides the core error handling functionality for the errors package.
|
Package core provides the core error handling functionality for the errors package. |
|
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
Package types provides specific error types for the errors package.
|
Package types provides specific error types for the errors package. |