errors

package
v1.19.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 13 Imported by: 0

README

Errors Package

Go Version GoDoc

Advanced error handling with error codes, tracing, hierarchy, and collection management.

AI Disclaimer (EU AI Act Article 50.4): AI assistance was used solely for testing, documentation, and bug resolution under human supervision.


Table of Contents


Overview

The errors package provides advanced error handling capabilities beyond Go's standard library. It adds error codes, automatic stack tracing, error hierarchies, and utilities for error collection and management.

Design Philosophy
  • Error Codes: Assign numeric codes for programmatic error identification
  • Tracing: Automatic file/line tracking for error origins
  • Hierarchy: Chain errors with parent-child relationships
  • Type Safety: Strongly typed error codes with constants
  • Compatibility: Works with standard Go error handling patterns
  • Performance: Minimal overhead with efficient error creation

Key Features

Feature Description
Error Codes Numeric error codes for classification
Stack Traces Automatic file/line number tracking
Error Hierarchy Parent-child error chains
Error Pool Thread-safe error collection (sub-package)
Code Constants Predefined HTTP-like error codes
Pattern Matching Search errors by code or message
Gin Integration Direct integration with Gin framework
Type Safe Strong typing for error codes

Architecture

Package Structure
errors/
├── interface.go        # Main Error interface
├── code.go            # Error code definitions and constants
├── errors.go          # Error creation and management
├── trace.go           # Stack trace functionality
├── return.go          # Error return helpers
├── compat.go          # Standard library compatibility
├── mode.go            # Error mode (dev/prod)
├── modules.go         # Module-specific errors
└── pool/              # Error collection sub-package
    ├── interface.go
    └── model.go
Error Architecture
┌─────────────────────────────────────────────────────┐
│                  Error Interface                     │
│                                                      │
│  ┌──────────────────────────────────────────────┐  │
│  │         Error Code (uint16)                  │  │
│  │  - Predefined constants (404, 500, etc.)     │  │
│  │  - Custom codes                              │  │
│  └──────────────────────────────────────────────┘  │
│                       │                              │
│  ┌──────────────────────────────────────────────┐  │
│  │         Stack Trace                          │  │
│  │  - File path                                 │  │
│  │  - Line number                               │  │
│  │  - Function name                             │  │
│  └──────────────────────────────────────────────┘  │
│                       │                              │
│  ┌──────────────────────────────────────────────┐  │
│  │         Error Hierarchy                      │  │
│  │  - Parent errors (chain)                     │  │
│  │  - Child errors                              │  │
│  │  - Multi-error support                       │  │
│  └──────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘
Error Flow
Error Creation → Code Assignment → Stack Trace → Hierarchy
       │              │                │              │
       ▼              ▼                ▼              ▼
   New Error    HTTP/Custom      File:Line      Add Parents
                   Code           Automatic       Optional

Sub-Packages

Pool Package

Purpose: Thread-safe error collection with automatic indexing

Features:

  • Concurrent error collection
  • Automatic sequential indexing
  • Sparse index support
  • Query operations (Get, Set, Del)
  • Combined error generation

Use Cases:

  • Batch operation error collection
  • Multi-goroutine error aggregation
  • Error accumulation in loops
  • Validation error collection

Documentation: pool/README.md

Quick Example:

import "github.com/nabbar/golib/errors/pool"

p := pool.New()

// Collect errors from multiple operations
for _, item := range items {
    if err := process(item); err != nil {
        p.Add(err)
    }
}

// Check if any errors occurred
if err := p.Error(); err != nil {
    return fmt.Errorf("processing failed: %w", err)
}

Test Coverage: 83 specs, 100% coverage, 0 race conditions


Quick Start

Basic Error Creation
package main

import (
    "fmt"
    liberr "github.com/nabbar/golib/errors"
)

func main() {
    // Create error with code
    err := liberr.NotFoundError.Error(nil)
    fmt.Println(err) // 404: Not Found
    
    // Create custom error
    customErr := liberr.New(func(code liberr.CodeError) liberr.Error {
        return code.Error(nil)
    }, 1001)
    fmt.Println(customErr.Code()) // 1001
}
With Stack Trace
func processData() error {
    // Stack trace automatically captured
    return liberr.InternalError.Error(nil)
}

func main() {
    if err := processData(); err != nil {
        if e, ok := err.(liberr.Error); ok {
            fmt.Printf("Error at %s:%d\n", e.GetFile(), e.GetLine())
        }
    }
}
Error Hierarchy
func operation() error {
    err1 := liberr.ValidationError.Error(nil)
    err2 := liberr.InternalError.Error(nil)
    
    // Chain errors
    mainErr := liberr.UnknownError.Error(nil)
    mainErr.Add(err1, err2)
    
    return mainErr
}

Error Codes

Predefined HTTP Codes
Code Constant Description
200 SuccessCode Success
400 BadRequestError Bad Request
401 UnauthorizedError Unauthorized
403 ForbiddenError Forbidden
404 NotFoundError Not Found
408 TimeoutError Request Timeout
409 ConflictError Conflict
422 ValidationError Validation Error
429 TooManyRequestsError Too Many Requests
500 InternalError Internal Error
501 NotImplementedError Not Implemented
503 ServiceUnavailableError Service Unavailable
Custom Error Codes
const (
    MyCustomError = liberr.CodeError(2000)
    DatabaseError = liberr.CodeError(2001)
    CacheError    = liberr.CodeError(2002)
)

func validateInput(data string) error {
    if len(data) == 0 {
        return MyCustomError.Error(nil)
    }
    return nil
}
Code Checking
err := liberr.NotFoundError.Error(nil)

// Check specific code
if err.(liberr.Error).IsCode(liberr.NotFoundError) {
    fmt.Println("Resource not found")
}

// Check in hierarchy
if err.(liberr.Error).HasCode(liberr.NotFoundError) {
    fmt.Println("Not found error in chain")
}

// Get code
code := err.(liberr.Error).GetCode()
fmt.Printf("Error code: %d\n", code)

Error Hierarchy

Creating Error Chains
// Bottom level error
dbErr := liberr.InternalError.Error(errors.New("database connection failed"))

// Mid level error
serviceErr := liberr.ServiceUnavailableError.Error(nil)
serviceErr.Add(dbErr)

// Top level error
apiErr := liberr.BadRequestError.Error(nil)
apiErr.Add(serviceErr)

// apiErr now contains: BadRequest → ServiceUnavailable → Internal → db error
Traversing Hierarchy
err := createComplexError()

// Get all parent errors
parents := err.GetParent(true) // includes main error
for _, e := range parents {
    fmt.Println(e)
}

// Check for specific error
if err.HasError(specificErr) {
    fmt.Println("Found specific error in chain")
}

// Map over all errors
err.Map(func(e error) bool {
    fmt.Println(e.Error())
    return true // continue
})
Error Unwrapping
// Compatible with errors.Is and errors.As
err := liberr.NotFoundError.Error(baseErr)

if errors.Is(err, baseErr) {
    fmt.Println("Error matches")
}

var target *SpecificError
if errors.As(err, &target) {
    fmt.Println("Error is SpecificError")
}

Stack Tracing

Automatic Tracing
func readFile(path string) error {
    // Error created here captures this location
    return liberr.NotFoundError.Error(nil)
}

func main() {
    if err := readFile("data.txt"); err != nil {
        if e, ok := err.(liberr.Error); ok {
            fmt.Printf("Error at %s:%d in %s\n", 
                e.GetFile(), 
                e.GetLine(),
                e.GetFunction())
        }
    }
}
Manual Tracing
err := liberr.New(func(code liberr.CodeError) liberr.Error {
    e := code.Error(nil)
    // Manually set trace
    e.SetTrace(runtime.Caller(0))
    return e
}, 1001)
Trace Information
err := liberr.InternalError.Error(nil)

if e, ok := err.(liberr.Error); ok {
    // Get trace details
    file := e.GetFile()      // "/path/to/file.go"
    line := e.GetLine()      // 42
    fn := e.GetFunction()    // "main.processData"
    
    // Format trace
    trace := e.GetTrace()    // "file.go:42"
    fullTrace := fmt.Sprintf("%s:%d %s", file, line, fn)
}

API Reference

Error Interface

Core Methods:

  • IsCode(code CodeError) bool - Check error code match
  • HasCode(code CodeError) bool - Check code in hierarchy
  • GetCode() CodeError - Get error code
  • Code() uint16 - Get numeric code

Hierarchy Methods:

  • Add(parent ...error) - Add parent errors
  • SetParent(parent ...error) - Replace parents
  • HasParent() bool - Check if has parents
  • GetParent(withMain bool) []error - Get parent chain
  • HasError(err error) bool - Find error in chain
  • Map(fct FuncMap) bool - Iterate over hierarchy

Trace Methods:

  • GetFile() string - Get source file
  • GetLine() int - Get line number
  • GetFunction() string - Get function name
  • GetTrace() string - Get formatted trace
  • SetTrace(pc uintptr, file string, line int, ok bool) - Set trace

Utility Methods:

  • Error() string - Standard error message
  • Is(e error) bool - Compatibility with errors.Is
  • ContainsString(s string) bool - Search in messages
  • CodeError(pattern string) string - Formatted code+message
CodeError Type
type CodeError uint16

// Create error from code
err := NotFoundError.Error(parentErr)

// Error creation
func (c CodeError) Error(parent error) Error

// Check if error exists
func (c CodeError) IfError(errs ...error) error
Helper Functions
// Create new error with function
func New(fct func(code CodeError) Error, code int) Error

// Create with return callback
func NewWithReturn(fct ReturnError, code int) Error

// Check if error contains code
func ErrorContainsCode(err error, codes ...CodeError) bool

Use Cases

HTTP API Error Handling
func getUser(id string) (*User, error) {
    user, err := db.FindUser(id)
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, liberr.NotFoundError.Error(err)
        }
        return nil, liberr.InternalError.Error(err)
    }
    return user, nil
}

func handleGetUser(c *gin.Context) {
    user, err := getUser(c.Param("id"))
    if err != nil {
        if e, ok := err.(liberr.Error); ok {
            c.JSON(int(e.Code()), gin.H{
                "error": e.Error(),
                "code": e.Code(),
            })
            return
        }
        c.JSON(500, gin.H{"error": "Internal error"})
        return
    }
    c.JSON(200, user)
}
Batch Operation Error Collection
import "github.com/nabbar/golib/errors/pool"

func processBatch(items []Item) error {
    p := pool.New()
    
    for i, item := range items {
        if err := validateItem(item); err != nil {
            p.Add(fmt.Errorf("item %d: %w", i, err))
        }
    }
    
    if p.Len() > 0 {
        return liberr.ValidationError.Error(p.Error())
    }
    
    return nil
}
Service Layer Error Translation
type UserService struct{}

func (s *UserService) CreateUser(data UserData) error {
    // Validation errors
    if err := data.Validate(); err != nil {
        return liberr.ValidationError.Error(err)
    }
    
    // Database errors
    if err := db.Insert(data); err != nil {
        if isDuplicateKey(err) {
            return liberr.ConflictError.Error(err)
        }
        return liberr.InternalError.Error(err)
    }
    
    return nil
}
Multi-Source Error Aggregation
func syncData() error {
    p := pool.New()
    
    var wg sync.WaitGroup
    
    // Sync from multiple sources concurrently
    sources := []string{"api1", "api2", "api3"}
    for _, src := range sources {
        wg.Add(1)
        go func(source string) {
            defer wg.Done()
            if err := syncFrom(source); err != nil {
                p.Add(fmt.Errorf("%s: %w", source, err))
            }
        }(src)
    }
    
    wg.Wait()
    
    if err := p.Error(); err != nil {
        return liberr.ServiceUnavailableError.Error(err)
    }
    
    return nil
}
Error Context Enrichment
func processRequest(req *Request) error {
    err := validateRequest(req)
    if err != nil {
        // Add context to error
        contextErr := liberr.ValidationError.Error(err)
        contextErr.Add(fmt.Errorf("request_id: %s", req.ID))
        contextErr.Add(fmt.Errorf("user_id: %s", req.UserID))
        return contextErr
    }
    
    return handleRequest(req)
}

Best Practices

1. Use Appropriate Error Codes
// ✅ Good: Use semantic codes
if user == nil {
    return liberr.NotFoundError.Error(nil)
}

if !hasPermission {
    return liberr.ForbiddenError.Error(nil)
}

// ❌ Bad: Generic errors
return errors.New("something went wrong")
2. Preserve Error Context
// ✅ Good: Wrap with context
if err := db.Query(); err != nil {
    return liberr.InternalError.Error(
        fmt.Errorf("query failed for user %s: %w", userID, err))
}

// ❌ Bad: Lose context
if err := db.Query(); err != nil {
    return liberr.InternalError.Error(nil)
}
3. Use Error Pool for Collections
// ✅ Good: Thread-safe collection
p := pool.New()
for _, item := range items {
    if err := process(item); err != nil {
        p.Add(err)
    }
}

// ❌ Bad: Manual slice management
var errs []error
for _, item := range items {
    if err := process(item); err != nil {
        errs = append(errs, err) // not thread-safe
    }
}
4. Check Error Codes Properly
// ✅ Good: Type assertion + check
if e, ok := err.(liberr.Error); ok {
    if e.IsCode(liberr.NotFoundError) {
        // Handle not found
    }
}

// ❌ Bad: String comparison
if strings.Contains(err.Error(), "not found") {
    // Fragile
}
5. Don't Ignore Stack Traces
// ✅ Good: Use trace in logs
if e, ok := err.(liberr.Error); ok {
    log.Printf("Error at %s:%d: %v", 
        e.GetFile(), e.GetLine(), e)
}

// ⚠️ Missing: Trace available but unused
log.Printf("Error: %v", err)

Testing

Comprehensive testing documentation is available in TESTING.md.

Quick Test:

cd errors
go test -v -cover
cd pool
go test -v -race -cover

Test Metrics:

  • Main Package: Comprehensive test suite with Ginkgo/Gomega
  • Pool Sub-Package: 83 specs, 100% coverage, 0 race conditions

Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass existing tests
  • Maintain backward compatibility
  • Follow existing code style

Testing

  • Write tests for all new features
  • Test error code behavior
  • Verify stack trace accuracy
  • Test error hierarchy operations
  • Include race detection tests for concurrent code

Documentation

  • Update README.md for new features
  • Add examples for common use cases
  • Document all public APIs with GoDoc
  • Keep TESTING.md synchronized

See CONTRIBUTING.md for detailed guidelines.


Go Standard Library
  • errors - Standard error handling
  • fmt - Error formatting
  • runtime - Stack trace information
HTTP Status Codes
  • atomic - Used by error pool
  • gin - Web framework integration

License

MIT License - See LICENSE file for details.

Copyright (c) 2020 Nicolas JUHEL


Resources


This package is part of the golib project.

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

View Source
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 = ""
)
View Source
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
)
View Source
const (
	PathSeparator = "/"
)

Variables

This section is empty.

Functions

func ContainsString added in v1.12.0

func ContainsString(e error, s string) bool

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 ConvPathFromLocal(str string) string

func ExistInMapMessage

func ExistInMapMessage(code CodeError) bool

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

func GetCodePackages(rootPackage string) map[CodeError]string

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

func Has(e error, code CodeError) bool

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

func Is(e error) bool

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

func IsCode(e error, code CodeError) bool

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

func RegisterIdFctMessage(minCode CodeError, fct Message)

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

func NewCodeError(code uint16) CodeError

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

func ParseCodeError(i int64) CodeError

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

func (c CodeError) Error(p ...error) 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

func (c CodeError) Errorf(args ...interface{}) Error

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

func (c CodeError) GetMessage() string

GetMessage returns the string representation of the CodeError value. Deprecated: see Message

func (CodeError) IfError

func (c CodeError) IfError(e ...error) Error

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

func (c CodeError) Int() int

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

func (c CodeError) Message() string

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

func (c CodeError) String() string

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

func (c CodeError) Uint16() uint16

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

func (*DefaultReturn) SetError added in v1.5.0

func (r *DefaultReturn) SetError(code int, msg string, file string, line int)

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

func AddOrNew(errMain, errSub error, parent ...error) Error

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

func Get(e error) Error

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 IfError added in v1.12.0

func IfError(code uint16, message string, parent ...error) Error

func Make added in v1.12.0

func Make(e error) Error

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

func MakeIfError(err ...error) Error

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

func New(code uint16, message string, parent ...error) Error

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 NewErrorRecovered(msg string, recovered string, parent ...error) Error

func NewErrorTrace added in v1.9.10

func NewErrorTrace(code int, msg string, file string, line int, parent ...error) Error

func Newf added in v1.19.0

func Newf(code uint16, pattern string, args ...any) Error

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 ErrorMode

type ErrorMode uint8
const (
	ModeDefault ErrorMode = iota
	ModeReturnCode
	ModeReturnCodeFull
	ModeReturnCodeError
	ModeReturnCodeErrorFull
	ModeReturnCodeErrorTrace
	ModeReturnCodeErrorTraceFull
	ModeReturnStringError
	ModeReturnStringErrorFull
)

func GetModeReturnError

func GetModeReturnError() ErrorMode

func (ErrorMode) String

func (m ErrorMode) String() string

type Errors added in v1.10.9

type Errors interface {
	// ErrorsLast return the last registered error
	ErrorsLast() error

	// ErrorsList return a slice of all registered errors
	ErrorsList() []error
}

type FuncMap added in v1.10.0

type FuncMap func(e error) bool

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

type Message func(code CodeError) (message string)

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

type ReturnError func(code int, msg string, file string, line int)

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)
}

Directories

Path Synopsis
Package pool provides a thread-safe error pool for collecting and managing multiple errors.
Package pool provides a thread-safe error pool for collecting and managing multiple errors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL