Documentation
¶
Overview ¶
Package errors provides structured application-specific error handling with integer error codes, error chaining, and seamless integration with zerolog structured logging.
Example (Chaining) ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
// Simulate a complex error scenario
dbErr := fmt.Errorf("connection lost")
err := errors.NewAppError(2001, "user operation failed").
WithCause(dbErr).
With("failed to update profile for user %s", "alice")
fmt.Printf("Final error: %s\n", err.Error())
fmt.Printf("Error code: %d\n", err.Code())
}
Output: Final error: failed to update profile for user alice: user operation failed: connection lost, code=2001 Error code: 2001
Example (PredefinedErrors) ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
// Using predefined errors
fmt.Printf("Success: '%s' (code: %d)\n", errors.Success.Error(), errors.Success.Code())
fmt.Printf("Not Found: '%s' (code: %d)\n", errors.ErrNotFound.Error(), errors.ErrNotFound.Code())
fmt.Printf("Unauthorized: '%s' (code: %d)\n", errors.ErrUnauthorized.Error(), errors.ErrUnauthorized.Code())
}
Output: Success: '' (code: 0) Not Found: 'not found, code=404' (code: 404) Unauthorized: 'unauthorized, code=401' (code: 401)
Index ¶
- Variables
- func Debug() *zerolog.Event
- func Error() *zerolog.Event
- func Fatal() *zerolog.Event
- func GetErrorCode(err error) int
- func Info() *zerolog.Event
- func Panic() *zerolog.Event
- func SetLogLevel(level zerolog.Level)
- func SetLogOutput(output io.Writer)
- func SetLogger(logger *zerolog.Logger)
- func Trace() *zerolog.Event
- func Warn() *zerolog.Event
- type AppCommonError
- func (e *AppCommonError) Code() int
- func (e *AppCommonError) Error() string
- func (e *AppCommonError) Is(target error) bool
- func (e *AppCommonError) LogDebug() AppError
- func (e *AppCommonError) LogError() AppError
- func (e *AppCommonError) LogFatal()
- func (e *AppCommonError) LogInfo() AppError
- func (e *AppCommonError) LogPanic()
- func (e *AppCommonError) LogTrace() AppError
- func (e *AppCommonError) LogWarn() AppError
- func (e *AppCommonError) Unwrap() error
- func (e *AppCommonError) With(format string, args ...any) AppError
- func (e *AppCommonError) WithCause(cause error) AppError
- type AppError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( Unknown = NewAppError(-1, "unknown error") ErrSystem = NewAppError(999999, "system error") // Common application errors ErrInvalidInput = NewAppError(400, "invalid input") ErrForbidden = NewAppError(403, "forbidden") ErrNotFound = NewAppError(404, "not found") ErrConflict = NewAppError(409, "conflict") ErrInternalError = NewAppError(500, "internal server error") )
var ( // DefaultLogger is the global zerolog logger instance used by this package's logging functions. DefaultLogger *zerolog.Logger // DefaultLogOutput is the default output writer for the logger if not set externally. DefaultLogOutput io.Writer = os.Stderr // DefaultLogLevel is the default log level for the logger if not set externally. DefaultLogLevel = zerolog.InfoLevel )
var (
Success = &AppCommonError{code: 0, err: nil}
)
Predefined common errors
Functions ¶
func Fatal ¶
Fatal returns a fatal level logger event, which will exit the application after logging.
func GetErrorCode ¶
GetErrorCode extracts the error code from an error, returns -1 if not an AppError
Example ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
appErr := errors.NewAppError(1005, "application error")
stdErr := fmt.Errorf("standard error")
fmt.Printf("AppError code: %d\n", errors.GetErrorCode(appErr))
fmt.Printf("Standard error code: %d\n", errors.GetErrorCode(stdErr))
}
Output: AppError code: 1005 Standard error code: -1
func SetLogLevel ¶
SetLogLevel sets the log level for the default logger
func SetLogOutput ¶
SetLogOutput sets the output writer for the default logger
Types ¶
type AppCommonError ¶
type AppCommonError struct {
// contains filtered or unexported fields
}
AppCommonError represents an error with a specific code and an underlying cause.
func IsAppError ¶
func IsAppError(err error) (*AppCommonError, bool)
IsAppError checks if an error is an AppError and returns it
Example ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
appErr := errors.NewAppError(1004, "application error")
stdErr := fmt.Errorf("standard error")
if extracted, ok := errors.IsAppError(appErr); ok {
fmt.Printf("AppError with code: %d\n", extracted.Code())
}
if _, ok := errors.IsAppError(stdErr); !ok {
fmt.Println("Not an AppError")
}
}
Output: AppError with code: 1004 Not an AppError
func (*AppCommonError) Code ¶
func (e *AppCommonError) Code() int
Code returns the application-specific error code.
func (*AppCommonError) Error ¶
func (e *AppCommonError) Error() string
Error implements the error interface.
func (*AppCommonError) Is ¶
func (e *AppCommonError) Is(target error) bool
Is reports whether this AppError matches the target AppError code.
func (*AppCommonError) LogDebug ¶
func (e *AppCommonError) LogDebug() AppError
LogDebug logs the AppError at debug level using the default logger.
func (*AppCommonError) LogError ¶
func (e *AppCommonError) LogError() AppError
LogError logs the AppError at error level using the default logger.
func (*AppCommonError) LogFatal ¶
func (e *AppCommonError) LogFatal()
LogFatal logs the AppError at fatal level using the default logger and exits.
func (*AppCommonError) LogInfo ¶
func (e *AppCommonError) LogInfo() AppError
LogInfo logs the AppError at info level using the default logger.
func (*AppCommonError) LogPanic ¶
func (e *AppCommonError) LogPanic()
LogPanic logs the AppError at panic level using the default logger and panics.
func (*AppCommonError) LogTrace ¶
func (e *AppCommonError) LogTrace() AppError
LogTrace logs the AppError at trace level using the default logger.
func (*AppCommonError) LogWarn ¶
func (e *AppCommonError) LogWarn() AppError
LogWarn logs the AppError at warn level using the default logger.
func (*AppCommonError) Unwrap ¶
func (e *AppCommonError) Unwrap() error
Unwrap returns the next error in the error chain.
func (*AppCommonError) With ¶
func (e *AppCommonError) With(format string, args ...any) AppError
With adds formatted context to the current AppError's underlying error chain. Returns a new AppError instance to avoid modifying the original.
Example ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
err := errors.NewAppError(1003, "validation failed")
contextErr := err.With("invalid email format for user %s", "john@")
fmt.Println(contextErr.Error())
}
Output: invalid email format for user john@: validation failed, code=1003
func (*AppCommonError) WithCause ¶
func (e *AppCommonError) WithCause(cause error) AppError
WithCause creates a new AppError instance based on the current AppError template (e)
Example ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
originalErr := fmt.Errorf("connection timeout")
appErr := errors.NewAppError(1002, "service unavailable")
wrappedErr := appErr.WithCause(originalErr)
fmt.Println(wrappedErr.Error())
}
Output: service unavailable: connection timeout, code=1002
type AppError ¶
type AppError interface {
error
Code() int
WithCause(cause error) AppError
With(format string, args ...any) AppError
Is(target error) bool
Unwrap() error
LogError() AppError
LogWarn() AppError
LogInfo() AppError
LogDebug() AppError
LogTrace() AppError
LogFatal()
LogPanic()
}
func NewAppError ¶
NewAppError creates a new basic AppCommonError instance with a code and a base message.
Example ¶
package main
import (
"fmt"
"github.com/gaoxing520/errors"
)
func main() {
err := errors.NewAppError(1001, "user not found")
fmt.Printf("Error: %s, Code: %d\n", err.Error(), err.Code())
}
Output: Error: user not found, code=1001, Code: 1001