Documentation
¶
Overview ¶
Package core provides the core error handling functionality for the application.
Package core provides the core error handling functionality for the errors package. It includes error codes, error context, and basic error types.
Package core provides the core error handling functionality for the errors package.
Package core provides the core error handling functionality for the errors package.
Index ¶
- Variables
- func As(err error, target interface{}) bool
- func BenchmarkContextualErrorCreation(b *testing.B)
- func BenchmarkErrorJSONMarshaling(b *testing.B)
- func BenchmarkErrorUnwrapping(b *testing.B)
- func BenchmarkErrorWrapping(b *testing.B)
- func BenchmarkGetCallerInfo(b *testing.B)
- func GetCallerInfo(skip int) (string, int)
- func GetHTTPStatus(code ErrorCode) int
- func GetHTTPStatusFromError(err error) int
- func Is(err error, target error) bool
- func ToJSON(err error) string
- func Unwrap(err error) error
- func WithContext(err error, operation string, code ErrorCode, httpStatus int, ...) error
- func WithDetails(err error, details map[string]interface{}) error
- func WrapWithOperation(err error, operation string) error
- type BaseError
- func (e *BaseError) As(target interface{}) bool
- func (e *BaseError) Error() string
- func (e *BaseError) GetCause() error
- func (e *BaseError) GetCode() ErrorCode
- func (e *BaseError) GetDetails() map[string]interface{}
- func (e *BaseError) GetHTTPStatus() int
- func (e *BaseError) GetLine() int
- func (e *BaseError) GetMessage() string
- func (e *BaseError) GetOperation() string
- func (e *BaseError) GetSource() string
- func (e *BaseError) Is(target error) bool
- func (e *BaseError) MarshalJSON() ([]byte, error)
- func (e *BaseError) Unwrap() error
- func (e *BaseError) WithDetails(details map[string]interface{}) *BaseError
- func (e *BaseError) WithOperation(operation string) *BaseError
- type ContextualError
- type ErrorCode
- type ErrorContext
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotFound is returned when a requested resource is not found ErrNotFound = fmt.Errorf("resource not found") // ErrAlreadyExists is returned when a resource already exists ErrAlreadyExists = fmt.Errorf("resource already exists") // ErrInvalidInput is returned when the input to a function is invalid ErrInvalidInput = fmt.Errorf("invalid input") // ErrInternal is returned when an internal error occurs ErrInternal = fmt.Errorf("internal error") ErrUnauthorized = fmt.Errorf("unauthorized") // ErrForbidden is returned when a user is forbidden from performing an action ErrForbidden = fmt.Errorf("forbidden") // ErrTimeout is returned when an operation times out ErrTimeout = fmt.Errorf("operation timed out") // ErrCancelled is returned when an operation is cancelled ErrCancelled = fmt.Errorf("operation cancelled") // ErrConflict is returned when there is a conflict with the current state ErrConflict = fmt.Errorf("conflict with current state") )
Standard errors that can be used throughout the application
var ErrorCodeToHTTPStatus = map[ErrorCode]int{ NotFoundCode: http.StatusNotFound, InvalidInputCode: http.StatusBadRequest, DatabaseErrorCode: http.StatusInternalServerError, InternalErrorCode: http.StatusInternalServerError, TimeoutCode: http.StatusGatewayTimeout, CanceledCode: http.StatusRequestTimeout, AlreadyExistsCode: http.StatusConflict, UnauthorizedCode: http.StatusUnauthorized, ForbiddenCode: http.StatusForbidden, ValidationErrorCode: http.StatusBadRequest, BusinessRuleViolationCode: http.StatusUnprocessableEntity, ExternalServiceErrorCode: http.StatusBadGateway, NetworkErrorCode: http.StatusServiceUnavailable, ConfigurationErrorCode: http.StatusInternalServerError, ResourceExhaustedCode: http.StatusTooManyRequests, DataCorruptionCode: http.StatusInternalServerError, ConcurrencyErrorCode: http.StatusConflict, }
Map of error codes to HTTP status codes
Functions ¶
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 BenchmarkErrorWrapping ¶
func BenchmarkGetCallerInfo ¶
func GetCallerInfo ¶
GetCallerInfo returns the file name and line number of the caller.
func GetHTTPStatus ¶
GetHTTPStatus returns the HTTP status code for an error code
func GetHTTPStatusFromError ¶
GetHTTPStatusFromError returns the HTTP status code from an error. If the error is a ContextualError, it returns the HTTP status from the context. If the error is a BaseError, it returns the HTTP status from the error code. Otherwise, it returns 500 (Internal Server Error). Parameters:
- err: The error to get the HTTP status from
Returns:
- int: The HTTP status code, or 500 if not available
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 ToJSON ¶
ToJSON converts an error to a JSON string. If the error is a BaseError, 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 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 WithContext ¶
func WithContext(err error, operation string, code ErrorCode, httpStatus int, details map[string]interface{}) error
WithContext wraps an error with contextual information. It adds operation name, error code, HTTP status, and source location to the error. If the error is already a ContextualError, it updates the context with the new information.
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. It preserves the error chain and adds source location information. Parameters:
- err: The error to wrap
- operation: The name of the operation that failed
Returns:
- error: A new error that wraps the original error
Types ¶
type BaseError ¶ added in v1.4.0
type BaseError struct { // Code is a unique error code for categorizing errors Code ErrorCode `json:"code,omitempty"` // Message is a human-readable error message Message string `json:"message,omitempty"` // Operation is the name of the operation that failed Operation string `json:"operation,omitempty"` // Details contains additional information about the error Details map[string]interface{} `json:"details,omitempty"` // Cause is the underlying error that caused this error Cause error `json:"-"` // 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"` }
BaseError is the foundation for all error types in the system. It provides common functionality for all errors, including error code, message, operation, details, cause, and stack trace.
func NewBaseError ¶ added in v1.4.0
NewBaseError creates a new BaseError with caller information.
func (*BaseError) GetDetails ¶ added in v1.4.0
GetDetails returns additional details about the error.
func (*BaseError) GetHTTPStatus ¶ added in v1.4.0
GetHTTPStatus returns the HTTP status code for the error.
func (*BaseError) GetLine ¶ added in v1.4.0
GetLine returns the line number where the error occurred.
func (*BaseError) GetMessage ¶ added in v1.4.0
GetMessage returns the error message.
func (*BaseError) GetOperation ¶ added in v1.4.0
GetOperation returns the operation that failed.
func (*BaseError) MarshalJSON ¶ added in v1.4.0
MarshalJSON implements the json.Marshaler interface.
func (*BaseError) WithDetails ¶ added in v1.4.0
WithDetails adds details to the error.
func (*BaseError) WithOperation ¶ added in v1.4.0
WithOperation adds an operation to the error.
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 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.
func GetCode ¶
GetCode returns the error code from an error. If the error is a ContextualError, it returns the code from the context. If the error is a BaseError, it returns the code from the BaseError. Otherwise, it returns InternalErrorCode. Parameters:
- err: The error to get the code from
Returns:
- ErrorCode: The error code, or InternalErrorCode if not available
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.