You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.2 KiB

package errs
import (
"fmt"
"strings"
)
// ErrCode is a custom error type that represents an error code.
// It may include a module and a value, separated by "::".
type ErrCode string
// MakeErrCode creates a new ErrCode from the given string.
// It validates that the string is non-empty and matches the predefined error code pattern.
// If the string is invalid, it panics.
func MakeErrCode(err string) ErrCode {
if len(err) == 0 || !g.codeValidator.MatchString(err) {
// If the error code is invalid, panic with a predefined error Msg.
fmt.Println(err)
panic(G.ErrInvalidErrCode)
}
// Return the created ErrCode.
return ErrCode(err)
}
// Error implements the error interface for ErrCode.
// It returns the error code as a string.
func (e ErrCode) Error() string {
return string(e)
}
// String returns the error code as a string representation.
func (e ErrCode) String() string {
return string(e)
}
// Module extracts and returns the module part of the error code.
// If there is no module, it returns an empty string.
func (e ErrCode) Module() string {
// Check if the error code has a module, using the module separator "::".
if b, has := strings.CutSuffix(string(e), ModuleSeparator); has {
return b
}
// If no module is found, return an empty string.
return ""
}
// Value extracts and returns the value part of the error code.
// If there is no value, it returns the entire error code.
func (e ErrCode) Value() string {
// Check if the error code has a value, using the module separator "::".
if b, has := strings.CutPrefix(string(e), ModuleSeparator); has {
return b
}
// If no module part is found, return the entire error code (it is considered as the value).
return string(e)
}
// IsValid checks whether the error code is valid according to the defined pattern.
// It returns true if the error code matches the regular expression, otherwise false.
func (e ErrCode) IsValid() bool {
// Use the code validator to check if the error code matches the pattern.
return g.codeValidator.MatchString(string(e))
}
// With returns a WrapErrWith instance containing this ErrCode
// Enables using the wrapper's additional error handling functionality
func (e ErrCode) With() ErrWith {
return MakeErrWith(e)
}

Powered by TurnKey Linux.