Documentation
¶
Overview ¶
Package errors provides advanced error handling with error codes, stack tracing, and hierarchy management.
This package extends Go's standard error handling with features for enterprise applications:
- Error codes (numeric classification similar to HTTP status codes)
- Automatic stack trace capture (file, line, function)
- Error hierarchy (parent-child error chains)
- Error collection management (via pool sub-package)
- Compatibility with standard errors.Is and errors.As
Key Features:
- Predefined HTTP-like error codes (404, 500, etc.)
- Custom error code support
- Automatic stack trace capture
- Error chaining and hierarchy
- Thread-safe error pool for collection
- Gin framework integration
Example usage:
import liberr "github.com/nabbar/golib/errors"
// Create error with code
err := liberr.NotFoundError.Error(nil)
fmt.Println(err.Code()) // 404
// With parent error
baseErr := errors.New("database connection failed")
err := liberr.InternalError.Error(baseErr)
// Check error code
if e, ok := err.(liberr.Error); ok {
if e.IsCode(liberr.InternalError) {
log.Printf("Internal error at %s:%d", e.GetFile(), e.GetLine())
}
}
// Error hierarchy
mainErr := liberr.UnknownError.Error(nil)
mainErr.Add(err1, err2, err3)
Sub-packages:
- pool: Thread-safe error collection with automatic indexing
Thread Safety:
The Error interface is not thread-safe for modification (Add, SetParent) but is safe for concurrent reads. Use the pool sub-package for thread-safe error collection across goroutines.
Index ¶
- Constants
- func ContainsString(e error, s string) bool
- func ConvPathFromLocal(str string) string
- func ExistInMapMessage(code CodeError) bool
- func GetCodePackages(rootPackage string) map[CodeError]string
- func GetDefaultPattern() string
- func GetDefaultPatternTrace() string
- func Has(e error, code CodeError) bool
- func Is(e error) bool
- func IsCode(e error, code CodeError) bool
- func RegisterIdFctMessage(minCode CodeError, fct Message)
- func SetDefaultPattern(pattern string)
- func SetDefaultPatternTrace(patternTrace string)
- func SetModeReturnError(mode ErrorMode)
- func SetTracePathFilter(path string)
- type CodeError
- func (c CodeError) Error(p ...error) Error
- func (c CodeError) Errorf(args ...interface{}) Error
- func (c CodeError) GetMessage() string
- func (c CodeError) IfError(e ...error) Error
- func (c CodeError) Int() int
- func (c CodeError) Message() string
- func (c CodeError) String() string
- func (c CodeError) Uint16() uint16
- type DefaultReturn
- func (r *DefaultReturn) AddParent(code int, msg string, file string, line int)
- func (r *DefaultReturn) GinTonicAbort(ctx *gin.Context, httpCode int)
- func (r *DefaultReturn) GinTonicErrorAbort(ctx *gin.Context, httpCode int)
- func (r *DefaultReturn) JSON() []byte
- func (r *DefaultReturn) SetError(code int, msg string, file string, line int)
- type Error
- func AddOrNew(errMain, errSub error, parent ...error) Error
- func Get(e error) Error
- func IfError(code uint16, message string, parent ...error) Error
- func Make(e error) Error
- func MakeIfError(err ...error) Error
- func New(code uint16, message string, parent ...error) Error
- func NewErrorRecovered(msg string, recovered string, parent ...error) Error
- func NewErrorTrace(code int, msg string, file string, line int, parent ...error) Error
- func Newf(code uint16, pattern string, args ...any) Error
- type ErrorMode
- type Errors
- type FuncMap
- type Message
- type Return
- type ReturnError
- type ReturnGin
Constants ¶
const ( // UnknownError represents an error with no specific code (0). // Used as a fallback when error code cannot be determined. UnknownError CodeError = 0 // UnknownMessage is the default message for UnknownError. UnknownMessage = "unknown error" // NullMessage represents an empty error message. NullMessage = "" )
const ( MinPkgArchive = baseInc + iota MinPkgArtifact = baseInc + MinPkgArchive MinPkgCertificate = baseInc + MinPkgArtifact MinPkgCluster = baseInc + MinPkgCertificate MinPkgConfig = baseInc + MinPkgCluster MinPkgConsole = moreInc + MinPkgConfig MinPkgCrypt = baseInc + MinPkgConsole MinPkgDatabaseGorm = baseInc + MinPkgCrypt MinPkgDatabaseKVDrv = baseSub + MinPkgDatabaseGorm MinPkgDatabaseKVMap = baseSub + MinPkgDatabaseKVDrv MinPkgDatabaseKVTbl = baseSub + MinPkgDatabaseKVMap MinPkgDatabaseKVItm = baseSub + MinPkgDatabaseKVTbl MinPkgFileProgress = baseInc + MinPkgDatabaseGorm MinPkgFTPClient = baseInc + MinPkgFileProgress MinPkgHttpCli = baseInc + MinPkgFTPClient MinPkgHttpCliDNSMapper = baseSub + MinPkgHttpCli MinPkgHttpServer = baseInc + MinPkgHttpCliDNSMapper MinPkgHttpServerPool = baseSub + MinPkgHttpServer MinPkgIOUtils = baseInc + MinPkgHttpServer MinPkgLDAP = baseInc + MinPkgIOUtils MinPkgLogger = baseInc + MinPkgLDAP MinPkgMail = baseInc + MinPkgLogger MinPkgMailer = baseInc + MinPkgMail MinPkgMailPooler = baseInc + MinPkgMailer MinPkgMonitor = baseInc + MinPkgMailPooler MinPkgMonitorCfg = baseSub + MinPkgMonitor MinPkgMonitorPool = baseSub + MinPkgMonitorCfg MinPkgNetwork = baseInc + MinPkgMonitor MinPkgNats = baseInc + MinPkgNetwork MinPkgNutsDB = baseInc + MinPkgNats MinPkgOAuth = baseInc + MinPkgNutsDB MinPkgAws = baseInc + MinPkgOAuth MinPkgRequest = baseInc + MinPkgAws MinPkgRouter = baseInc + MinPkgRequest MinPkgSemaphore = baseInc + MinPkgRouter MinPkgSMTP = baseInc + MinPkgSemaphore MinPkgSMTPConfig = baseInc + MinPkgSMTP MinPkgStatic = baseInc + MinPkgSMTPConfig MinPkgStatus = baseInc + MinPkgStatic MinPkgSocket = baseInc + MinPkgStatus MinPkgVersion = baseInc + MinPkgSocket MinPkgViper = baseInc + MinPkgVersion MinAvailable = baseInc + MinPkgViper )
const (
PathSeparator = "/"
)
Variables ¶
This section is empty.
Functions ¶
func ContainsString ¶ added in v1.12.0
ContainsString checks if the given error message contains the given string.
Parameters: - e (error): the error to be checked - s (string): the string to be searched for in the error message
Returns: - bool: true if the given error message contains the given string, false otherwise
func ConvPathFromLocal ¶ added in v1.9.17
func ExistInMapMessage ¶
ExistInMapMessage checks if a message is registered for a CodeError value.
It takes a CodeError value as argument and returns a boolean value. The returned boolean value is true if the CodeError value is registered and has a message associated with it. Otherwise, it returns false.
The function is used to check if a CodeError value is registered and has a message associated with it. If the CodeError value is not registered, it returns false.
The function is used in conjunction with the RegisterIdFctMessage function to register and check for CodeError values.
Example:
func testMessage(code CodeError) string {
switch code {
case MyErrorCode:
return "Test error message"
default:
return UnknownMessage
}
}
if ExistInMapMessage(MyErrorCode) {
panic("CodeError collision detected")
}
RegisterIdFctMessage(MyErrorCode, testMessage)
func GetCodePackages ¶ added in v1.5.1
GetCodePackages returns a map of CodeError to string that contains the path of the files associated with the CodeError.
It takes the root package name as argument and return a map where the key is the CodeError and the value is the file path associated with the CodeError. The returned map contains only the CodeError that are registered and has a file path associated with them.
The file path is a relative path from the root package. If the file path contains "/vendor/", it is removed from the path. If the file path starts with the root package, it is removed from the path. If the file path does not start with "/", it is prefixed with "/".
The returned map is empty if no CodeError is registered or if no file path is associated with any CodeError.
func GetDefaultPattern ¶
func GetDefaultPattern() string
GetDefaultPattern return the current pattern used for string of error with code. The pattern is fmt pattern with 2 inputs in order : code, message.
func GetDefaultPatternTrace ¶
func GetDefaultPatternTrace() string
GetDefaultPatternTrace return the current pattern used for string of error with code and trace. The pattern is fmt pattern with 3 inputs in order : code, message, trace.
func Has ¶ added in v1.12.0
Has checks if the given error or its parent has the given error code.
Parameters: - e (error): the error to be checked - code (CodeError): the error code to be checked
Returns: - bool: true if the given error or its parent has the given error code, false otherwise
func Is ¶ added in v1.12.0
Is checks if the given error is of type Error. It uses the errors.As function to check if the given error can be asserted to the Error interface.
Parameters: - e (error): the error to be checked
Returns: - bool: true if the given error is of type Error, false otherwise
func IsCode ¶ added in v1.12.0
IsCode checks if the given error has the given error code.
Parameters: - e (error): the error to be checked - code (CodeError): the error code to be checked
Returns: - bool: true if the given error has the given error code, false otherwise
func RegisterIdFctMessage ¶
RegisterIdFctMessage registers a message function associated with a CodeError value.
The message function takes a CodeError value as argument and returns a string. The returned string is the message associated with the CodeError value. The message function must return a non-empty string.
The registered message function is stored in a map where the key is the CodeError value and the value is the message function. The map is ordered by the CodeError value.
The message function is used to get the message associated with a CodeError value. If the CodeError value is not registered, it returns an empty string.
The minimum CodeError value is required to ensure that the message function is registered with the correct CodeError value.
The returned message string is empty if the CodeError value is not registered.
Example:
func testMessage(code CodeError) string {
switch code {
case MyErrorCode:
return "Test error message"
default:
return UnknownMessage
}
}
RegisterIdFctMessage(MyErrorCode, testMessage)
err := MyErrorCode.Error() fmt.Println(err.Message()) // "Test error message"
func SetDefaultPattern ¶
func SetDefaultPattern(pattern string)
GetDefaultPatternTrace define the pattern to be used for string of error with code. The pattern is fmt pattern with 2 inputs in order : code, message.
func SetDefaultPatternTrace ¶
func SetDefaultPatternTrace(patternTrace string)
SetDefaultPatternTrace define the pattern to be used for string of error with code and trace. The pattern is fmt pattern with 3 inputs in order : code, message, trace.
func SetModeReturnError ¶
func SetModeReturnError(mode ErrorMode)
func SetTracePathFilter ¶ added in v1.3.0
func SetTracePathFilter(path string)
SetTracePathFilter customize the filter apply to filepath on trace.
Types ¶
type CodeError ¶
type CodeError uint16
CodeError represents a numeric error code similar to HTTP status codes. It is a uint16 allowing codes from 0 to 65535. Predefined codes follow HTTP conventions (200, 404, 500, etc.).
func NewCodeError ¶ added in v1.19.0
NewCodeError returns a CodeError value based on the input uint16 value.
It is a simple wrapper around the type conversion from uint16 to CodeError.
The returned value is the same as the input uint16 value, but with a different type. This can be useful when interacting with functions or methods that expect or return a CodeError value.
func ParseCodeError ¶ added in v1.19.0
ParseCodeError returns a CodeError value based on the input int64 value. If the input value is negative, it returns UnknownError. If the input value is greater than or equal to math.MaxUint16, it returns math.MaxUint16. Otherwise, it returns the input value as a CodeError.
func (CodeError) Error ¶
Error returns an error value based on the CodeError value. It takes a variable number of parent errors as arguments. The returned error value is a new instance of the `Error` type. The CodeError value is used to set the code and message of the returned error value. The parent errors are stored in the `Error.Parent` field. If the CodeError value is UnknownError, it sets the code to UnknownError and the message to UnknownMessage. If the CodeError value is registered, it sets the code to the CodeError value and the message to the associated message string. Otherwise, it sets the code to UnknownError and the message to UnknownMessage.
func (CodeError) Errorf ¶ added in v1.19.0
Errorf returns an error value based on the CodeError value and arguments. It takes a variable number of arguments as arguments. The returned error value is a new instance of the `Error` type.
The CodeError value is used to set the code and message of the returned error value. The arguments are used to format the message string.
If the message string does not contain any "%" characters, it returns a new error value with the message string as is. If the message string contains "%" characters, it formats the message string using the arguments and returns a new error value with the formatted message string.
The number of arguments must be less than or equal to the number of "%" characters in the message string. If the number of arguments is greater than the number of "%" characters in the message string, it ignores the extra arguments.
If the CodeError value is UnknownError, it sets the code to UnknownError and the message to UnknownMessage. If the CodeError value is registered, it sets the code to the CodeError value and the message to the associated message string.
Otherwise, it sets the code to UnknownError and the message to UnknownMessage.
func (CodeError) GetMessage ¶
GetMessage returns the string representation of the CodeError value. Deprecated: see Message
func (CodeError) IfError ¶
IfError returns an error value based on the CodeError value and parent error. The Error is returned only if the filtered parent list contain a valid error (not nil and with a string result). Otherwise, the return value is nil.
It takes the CodeError value, its associated message string, and a parent error as arguments. The returned error value is a new instance of the `Error` type. The CodeError value is used to set the code and message of the returned error value. The parent error is stored in the `Error.Parent` field.
If the CodeError value is UnknownError, it sets the code to UnknownError and the message to UnknownMessage. If the CodeError value is registered, it sets the code to the CodeError value and the message to the associated message string. Otherwise, it sets the code to UnknownError and the message to UnknownMessage.
func (CodeError) Int ¶ added in v1.19.0
Int returns the CodeError value as an int.
It is a simple wrapper around the type conversion from CodeError to int.
The returned value is the same as the CodeError value, but with a different type. This can be useful when interacting with functions or methods that expect or return an int value.
func (CodeError) Message ¶ added in v1.19.0
Message returns a string representation of the CodeError value. If the CodeError value is registered and not the UnknownError code, it returns the associated message string. Otherwise, it returns UnknownMessage.
func (CodeError) String ¶ added in v1.19.0
String returns a string representation of the CodeError value.
The returned string is the same as the CodeError value, but with a different type. This can be useful when interacting with functions or methods that expect or return a string value.
func (CodeError) Uint16 ¶ added in v1.19.0
Uint16 returns the CodeError value as a uint16.
It is a simple wrapper around the type conversion from CodeError to uint16.
The returned value is the same as the CodeError value, but with a different type. This can be useful when interacting with functions or methods that expect or return a uint16 value.
type DefaultReturn ¶ added in v1.5.0
type DefaultReturn struct {
ReturnGin
Code string
Message string
// contains filtered or unexported fields
}
func NewDefaultReturn ¶ added in v1.5.0
func NewDefaultReturn() *DefaultReturn
func (*DefaultReturn) AddParent ¶ added in v1.5.0
func (r *DefaultReturn) AddParent(code int, msg string, file string, line int)
func (*DefaultReturn) GinTonicAbort ¶ added in v1.5.0
func (r *DefaultReturn) GinTonicAbort(ctx *gin.Context, httpCode int)
func (*DefaultReturn) GinTonicErrorAbort ¶ added in v1.5.0
func (r *DefaultReturn) GinTonicErrorAbort(ctx *gin.Context, httpCode int)
func (*DefaultReturn) JSON ¶ added in v1.5.0
func (r *DefaultReturn) JSON() []byte
type Error ¶
type Error interface {
error
// IsCode checks if the error's code matches the given code.
// Returns true only if the error's direct code equals the provided code.
// Does not check parent errors.
IsCode(code CodeError) bool
//HasCode check if current error or parent has the given error code
HasCode(code CodeError) bool
//GetCode return the CodeError value of the current error
GetCode() CodeError
//GetParentCode return a slice of CodeError value of all parent Error and the code of the current Error
GetParentCode() []CodeError
//Is implement compatibility with root package errors Is function
Is(e error) bool
//IsError check if the given error params is a valid error and not a nil pointer
IsError(e error) bool
//HasError check if the given error in params is still in parent error
HasError(err error) bool
//HasParent check if the current Error has any valid parent
HasParent() bool
//GetParent return a slice of Error interface for each parent error with or without the first error.
GetParent(withMainError bool) []error
//Map run a function on each func and parent. If the function return false, the loop stop.
Map(fct FuncMap) bool
//ContainsString return true if any message into the main error or the parent message error contains the given part string
ContainsString(s string) bool
//Add will add all no empty given error into parent of the current Error pointer
Add(parent ...error)
//SetParent will replace all parent with the given error list
SetParent(parent ...error)
//Code is used to return the code of current Error, as string
Code() uint16
//CodeSlice is used to return a slice string of all code of current Error (main and parent)
CodeSlice() []uint16
//CodeError is used to return a composed string of current Error code with message, for current Error and no parent
CodeError(pattern string) string
//CodeErrorSlice is used to return a composed string slice of couple error code with message, for current Error and all parent
CodeErrorSlice(pattern string) []string
//CodeErrorTrace is used to return a composed string of current Error code with message and trace information, for current Error and no parent
CodeErrorTrace(pattern string) string
//CodeErrorTraceSlice is used to return a composed string slice of couple error code with message and trace information, for current Error and all parent
CodeErrorTraceSlice(pattern string) []string
//Error is used to match with error interface
//this function will return a mixed result depends of the configuration defined by calling SetModeReturnError
Error() string
//StringError is used to return the error message, for current Error and no parent
StringError() string
//StringErrorSlice is used to return the error message, for current Error and all parent, as a slice of string
StringErrorSlice() []string
//GetError is used to return a new error interface based of the current error (and no parent)
GetError() error
//GetErrorSlice is used to return a slice of new error interface, based of the current error and all parent
GetErrorSlice() []error
//Unwrap will set compliance with errors As/Is functions
Unwrap() []error
//GetTrace will return a comped string for the trace of the current Error
GetTrace() string
//GetTrace will return a slice of comped string fpr the trace of the current Error and all parent
GetTraceSlice() []string
//Return will transform the current Error into a given pointer that implement the Return interface
Return(r Return)
//ReturnError will send the current Error value to the given function ReturnError
ReturnError(f ReturnError)
//ReturnParent will send all parent information of the current Error value to the given function ReturnError
ReturnParent(f ReturnError)
}
Error is the main interface extending Go's standard error with additional capabilities.
This interface provides:
- Error code management (numeric classification)
- Error hierarchy (parent-child relationships)
- Stack trace information (file, line, function)
- Pattern matching and searching
- Compatibility with errors.Is and errors.As
All methods are safe for concurrent reads but modification methods (Add, SetParent) are not thread-safe. Use the pool sub-package for thread-safe error collection.
func AddOrNew ¶ added in v1.12.0
AddOrNew takes an error and an error to be added to it. It also takes a variable number of parent errors.
If the main error is not nil, it will be converted to an Error interface if it is not of type Error. The given error to be added and the parent errors will be added to the Error interface.
If the main error is nil and the error to be added is not nil, a new Error interface will be created with the given error and parent errors.
If both the main error and the error to be added are nil, nil will be returned.
Parameters: - errMain (error): the main error to be converted to an Error interface - errSub (error): the error to be added to the main error - parent (error): a variable number of parent errors to be added to the main error
Returns: - Error: the given errors as an Error interface if the main error or the error to be added is not nil, nil otherwise.
func Get ¶ added in v1.12.0
Get checks if the given error is of type Error and returns the Error interface if it is.
Parameters: - e (error): the error to be checked
Returns: - Error: the given error as an Error interface if it is of type Error, nil otherwise
func Make ¶ added in v1.12.0
Make takes an error and returns an Error interface if the given error is of type Error. If the given error is not of type Error, it will be wrapped in an Error interface with code 0.
Parameters: - e (error): the error to be converted to an Error interface
Returns: - Error: the given error as an Error interface if it is of type Error, otherwise a new Error interface wrapping the given error with code 0.
func MakeIfError ¶ added in v1.12.0
MakeIfError takes a variable number of errors and returns an Error interface if any of the given errors is not nil. If all the given errors are nil, it will return nil. If any of the given errors are of type Error, it will be added to the Error interface. If any of the given errors are not of type Error, it will be wrapped in an Error interface with code 0 and added to the Error interface.
Parameters: - err (error): a variable number of errors to be converted to an Error interface
Returns: - Error: the given errors as an Error interface if any of the given errors is not nil, nil otherwise.
func New ¶ added in v1.12.0
New creates a new Error interface with the given code, message, and parent errors.
Parameters: - code (uint16): the code of the error - message (string): the message of the error - parent (error): a variable number of parent errors to be added to the error
Returns: - Error: the given code, message, and parent errors as an Error interface
func NewErrorRecovered ¶ added in v1.9.11
func NewErrorTrace ¶ added in v1.9.10
func Newf ¶ added in v1.19.0
Newf creates a new Error interface with the given code and a message generated by calling fmt.Sprintf with the given pattern and arguments.
Parameters: - code (uint16): the code of the error - pattern (string): the pattern to be used with fmt.Sprintf - args (any): the arguments to be used with fmt.Sprintf
Returns: - Error: the given code and message as an Error interface
type FuncMap ¶ added in v1.10.0
FuncMap is a callback function type used for iterating over error hierarchies. It receives each error in the chain and returns true to continue iteration or false to stop.
Example:
err.Map(func(e error) bool {
log.Println(e.Error())
return true // continue to next error
})
type Message ¶
Message is a function type that generates error messages based on error codes. It allows dynamic message generation or customization per error code.
type Return ¶ added in v1.5.0
type Return interface {
// SetError set the error with the given code, message, file and line.
//
// It will create a new error with the given information and append it to the current error list.
// If the error list is empty, it will create a new one.
//
// Parameters:
// - code (int): error code
// - msg (string): error message
// - file (string): file where the error occurs
// - line (int): line where the error occurs
SetError(code int, msg string, file string, line int)
// AddParent is used to add a parent error to the current error.
//
// It will create a new error with the given information and add it to the parent error list of the current error.
//
// Parameters:
// - code (int): error code
// - msg (string): error message
// - file (string): file where the error occurs
// - line (int): line where the error occurs
AddParent(code int, msg string, file string, line int)
// JSON return the JSON representation of the current error.
//
// It will generate a JSON object with the following structure:
// {
// "code": <int>,
// "msg": <string>,
// "parents": [
// {
// "code": <int>,
// "msg": <string>,
// "file": <string>,
// "line": <int>
// }
// ]
// }
//
// Parameters: None
//
// Returns: []byte, a JSON representation of the current error
JSON() []byte
}
type ReturnError ¶ added in v1.5.0
ReturnError is a callback function type for custom error return handling. It receives error details (code, message, file, line) and can be used to implement custom error reporting or logging mechanisms.
type ReturnGin ¶ added in v1.10.0
type ReturnGin interface {
Return
// GinTonicAbort is used to abort the current request with the given HTTP status code.
//
// It will write the JSON representation of the current error to the response writer with the given HTTP status code.
//
// Parameters:
// - ctx (*gin.Context): the gin context
// - httpCode (int): the HTTP status code to return
//
// Returns: None
GinTonicAbort(ctx *gin.Context, httpCode int)
// GinTonicErrorAbort is used to abort the current request with the given HTTP status code,
// and write the JSON representation of the current error to the response writer.
//
// Parameters:
// - ctx (*gin.Context): the gin context
// - httpCode (int): the HTTP status code to return
//
// Returns: None
GinTonicErrorAbort(ctx *gin.Context, httpCode int)
}