errors

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2025 License: MIT Imports: 12 Imported by: 0

README

errors Package

The errors package provides a comprehensive framework for error handling in Go, supporting error codes, messages, parent/child error relationships, stack traces, and integration with web frameworks like Gin. It is designed to facilitate structured, traceable, and user-friendly error management in complex applications.

Features

  • Custom error type with code, message, and parent errors
  • Error code registration and message mapping
  • Stack trace capture and filtering
  • Error wrapping and unwrapping (compatible with Go's standard errors package)
  • Flexible error formatting modes (code, message, trace, etc.)
  • Integration with Gin for HTTP error responses
  • Utilities for error lists, code checks, and string search

Main Types & Interfaces

Error Interface

Represents a single error with code, message, trace, and parent errors. Key methods:

  • IsCode(code CodeError) bool: Checks if the error has the given code.
  • HasCode(code CodeError) bool: Checks if the error or any parent has the code.
  • GetCode() CodeError: Returns the error code.
  • GetParentCode() []CodeError: Returns all codes in the error chain.
  • Is(e error) bool: Checks if the error matches another error (compatible with errors.Is).
  • HasError(err error) bool: Checks if the error or any parent matches the given error.
  • HasParent() bool: Returns true if there are parent errors.
  • GetParent(withMainError bool) []error: Returns all parent errors.
  • Map(fct FuncMap) bool: Applies a function to the error and all parents.
  • ContainsString(s string) bool: Checks if the message contains a substring.
  • Add(parent ...error): Adds parent errors.
  • SetParent(parent ...error): Replaces parent errors.
  • Code() uint16: Returns the code as uint16.
  • CodeSlice() []uint16: Returns all codes in the chain.
  • CodeError(pattern string) string: Formats the error with code and message.
  • CodeErrorTrace(pattern string) string: Formats with code, message, and trace.
  • Error() string: Returns the error string (format depends on mode).
  • StringError() string: Returns the error message.
  • GetError() error: Returns a standard error.
  • Unwrap() []error: Returns parent errors for Go error unwrapping.
  • GetTrace() string: Returns the stack trace.
  • Return(r Return): Fills a Return struct for API responses.
Errors Interface
  • ErrorsLast() error: Returns the last error.
  • ErrorsList() []error: Returns all errors.
Return and ReturnGin Interfaces

For API error responses, including Gin integration.


Error Creation & Usage

Creating Errors
import "github.com/nabbar/golib/errors"

err := errors.New(1001, "Something went wrong")
err2 := errors.New(1002, "Another error", err)
Wrapping and Checking Errors
if errors.IsCode(err, 1001) {
    // handle specific error code
}

if errors.ContainsString(err, "wrong") {
    // handle error containing substring
}
Error Formatting Modes

Set the global error formatting mode:

errors.SetModeReturnError(errors.ErrorReturnCodeErrorTrace)

Modes include: code only, code+message, code+message+trace, message only, etc.

Gin Integration
import "github.com/gin-gonic/gin"

var r errors.DefaultReturn
err.Return(&r)
r.GinTonicAbort(ctx, 500)

Error Codes & Messages

  • Register custom error codes and messages using RegisterIdFctMessage.
  • Retrieve code locations with GetCodePackages.

Stack Traces

  • Each error captures the file, line, and function where it was created.
  • Traces are filtered to remove vendor and runtime paths.

Notes

  • Fully compatible with Go's errors.Is and errors.As.
  • Supports error chaining and parent/child relationships.
  • Designed for use in both CLI and web applications.

Voici une section de documentation en anglais pour aider les développeurs à définir et enregistrer des codes d'erreur personnalisés avec le package github.com/nabbar/golib/errors :


Defining and Registering Custom Error Codes

To create your own error codes and messages with the errors package, follow these steps:

1. Define Error Code Constants

Define your error codes as constants of type liberr.CodeError. Use an offset (e.g., your package's minimum code) to avoid collisions with other packages:

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

const (
    MyErrorInvalidParam liberr.CodeError = iota + liberr.MinPkgMyFeature
    MyErrorFileNotFound
    MyErrorProcessingFailed
)
2. Register Message Retrieval Function

Implement a function that returns a message for each error code, and register it using liberr.RegisterIdFctMessage in an init() function. Before registering, check for code collisions with liberr.ExistInMapMessage:

func init() {
    if liberr.ExistInMapMessage(MyErrorInvalidParam) {
        panic(fmt.Errorf("error code collision with package myfeature"))
    }
    liberr.RegisterIdFctMessage(MyErrorInvalidParam, getMyFeatureErrorMessage)
}

func getMyFeatureErrorMessage(code liberr.CodeError) string {
    switch code {
    case MyErrorInvalidParam:
        return "invalid parameter provided"
    case MyErrorFileNotFound:
        return "file not found"
    case MyErrorProcessingFailed:
        return "processing failed"
    }
    return liberr.NullMessage
}
3. Usage Example

Create and use your custom errors as follows:

err := MyErrorInvalidParam.Error(fmt.Errorf("additional context: %s", "details"))

And check for specific error codes or messages:

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

if liberr.IsCode(err, MyErrorInvalidParam) {
    // handle specific error
}

if e := Get(err); e != nil && e.HasParent() {
    for _, parent := range err.GetParent(true) {
        fmt.Println("Parent error:", parent)
    }
}

if ContainsString(err, "missing") {
    // handle error containing substring
}

if e := Get(err); e != nil {
    fmt.Println("Error code:", e.Code())
    fmt.Println("Error message:", e.StringError())
	fmt.Println("Error trace:", e.GetTrace())
	for _, oneErr := range e.GetErrorSlice() {
        fmt.Println("Error code in slice:", oneErr.Code())
		fmt.Println("Error message:", oneErr.StringError())
        fmt.Println("Error trace:", oneErr.GetTrace())
	}
}


Notes:

  • Always check for code collisions before registering new error codes.
  • Use a unique offset for your package to avoid overlapping with other packages.
  • Register a message function for each error code group to provide meaningful error messages.

Documentation

Index

Constants

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

Variables

This section is empty.

Functions

func ContainsString added in v1.12.0

func ContainsString(e error, s string) bool

func ConvPathFromLocal added in v1.9.17

func ConvPathFromLocal(str string) string

func ExistInMapMessage

func ExistInMapMessage(code CodeError) bool

func GetCodePackages added in v1.5.1

func GetCodePackages(rootPackage string) map[CodeError]string

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

func Is added in v1.12.0

func Is(e error) bool

func IsCode added in v1.12.0

func IsCode(e error, code CodeError) bool

func RegisterIdFctMessage

func RegisterIdFctMessage(minCode CodeError, fct 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
const UnknownError CodeError = 0

func (CodeError) Error

func (c CodeError) Error(p ...error) Error

func (CodeError) GetInt

func (c CodeError) GetInt() int

func (CodeError) GetMessage

func (c CodeError) GetMessage() string

func (CodeError) GetString

func (c CodeError) GetString() string

func (CodeError) GetUint16

func (c CodeError) GetUint16() uint16

func (CodeError) IfError

func (c CodeError) IfError(e error) Error

type DefaultReturn added in v1.5.0

type DefaultReturn struct {
	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 check if the given error code is matching with the current Error
	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 compatiblity with GOROOT/src/errors/wrap Is fucntion
	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)
}

func AddOrNew added in v1.12.0

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

func Get added in v1.12.0

func Get(e error) Error

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

func MakeIfError added in v1.12.0

func MakeIfError(err ...error) Error

func New added in v1.12.0

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

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

type ErrorMode

type ErrorMode uint8
const (
	Default ErrorMode = iota
	ErrorReturnCode
	ErrorReturnCodeFull
	ErrorReturnCodeError
	ErrorReturnCodeErrorFull
	ErrorReturnCodeErrorTrace
	ErrorReturnCodeErrorTraceFull
	ErrorReturnStringError
	ErrorReturnStringErrorFull
)

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

type Message

type Message func(code CodeError) (message string)

type Return added in v1.5.0

type Return interface {
	SetError(code int, msg string, file string, line int)
	AddParent(code int, msg string, file string, line int)
	JSON() []byte
}

type ReturnError added in v1.5.0

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

type ReturnGin added in v1.10.0

type ReturnGin interface {
	Return

	GinTonicAbort(ctx *gin.Context, httpCode int)
	GinTonicErrorAbort(ctx *gin.Context, httpCode int)
}

Jump to

Keyboard shortcuts

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