perrors

package
v0.4.122 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2023 License: ISC Imports: 7 Imported by: 11

Documentation

Overview

Package perrors enrichens error values with string data, stack traces, associated errors, less severe warnings, thread-safe containers and comprehensive error string representations.

Creating errors with stack traces:

err := error116.New("error message") // adds a stacktrace contained inside of err
err = error116.Errorf("Some text: '%w'", err) // adds a stacktrace if err does not already have it
err = error116.Stackn(err, 0) // adds a stack trace even if err already has it

Enriching errors:

err = error116.AddKeyValue(err, "record", "123") // adds a key-value string, last key wins
err = error116.AddKeyValue(err, "", "2022-03-19 11:10:00") // adds a string to a list, oldest first

Encapsulating associated errors allowing for a single error value to contain multiple errors:

err = error116.AppendError(err, err2) // err2 is inside of err, can be printed and retrieved
fn := error116.Errp(&err) // fn(error) can be repeatedly invoked, aggregating errors in err
error116.ParlError.AddError(err) // thread-safe error encapsulation

Marking errors as less severe:

warning := error116.Warning(err) // warning should not terminate the thread
error116.IsWarning(err) // Determine severity of an error value

Printing rich errors:

error116.Long(err)
→ error-message
→ github.com/haraldrudell/parl/error116.(*csTypeName).FuncName
→   /opt/sw/privates/parl/error116/chainstring_test.go:26
→ runtime.goexit
→   /opt/homebrew/Cellar/go/1.17.8/libexec/src/runtime/asm_arm64.s:1133
→ record: 1234
→ Other error: Close failed
error116.Short(err)
→ error-message at error116.(*csTypeName).FuncName-chainstring_test.go:26
fmt.Println(err)
→ error-message

Can be used with Printf, but only works if last error in chain is from error116:

fmt.Printf("err: %+v", err) // same as Long()
fmt.Printf("err: %-v", err) // save as Short()

Is compatible:

fmt.Println(err) // no change
fmt.Printf("err: %v", err) // no change
err.Error() // no change
fmt.Printf("err: %s", err) // no change
fmt.Printf("err: %q", err) // no change

perrors used to be called error116 becaue Rob Pike was going to put it into go1.16

© 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddKeyValue

func AddKeyValue(err error, key, value string) (e error)

error116.AddKeyValue attaches a string value to err. The values can be trrioeved using error116.ErrorData(). if key is non-empty valiue is returned in a map where last key wins. if key is empty, valuse is returned in s string slice. err can be nil.

func AppendError

func AppendError(err error, err2 error) (e error)

AppendError associates an additional error with err.

  • return value is nil if and only if both err and err2 are nil
  • if either err or err2 is nil, return value is the non-nil argument
  • if both err and err2 are non-nil, the return value is err with err2 associated
  • associated error instances can be retrieved using:
  • — perrors.AllErrors,
  • — perros.ErrorList or
  • — by rich error printing of perrors package: perrors.Long or
  • — “%+v”

func AppendErrorDefer added in v0.4.56

func AppendErrorDefer(errp, errp2 *error, fn func() (err error))

AppendErrorDefer aggregates error sources into errp.

  • AppendErrorDefer is deferrable
  • errp cannot be nil
  • errp2 is a pointer to a second error variable used as source. If errp2 is nil or *errp2 is nil, no action is taken
  • fn is a function returning a possible error. If fn is nil or fn returns nil, no action is taken
  • AppendErrorDefer uses AppendError to aggregate error values into *errp

func Deferr added in v0.4.17

func Deferr(label string, errp *error, fn func(format string, a ...interface{})) string

Deferr invokes a printing function for an error pointer. Deferr returns the message. Deferr is deferrable. A colon and a space is appended to label. If *errp is nil, OK is printed. If errp is nil, a message is printed. if fn is nil, nothing is printed. If *errp contains an error it is printed in Short form:

label: Error message at error116.(*csTypeName).FuncName-chainstring_test.go:26

func Error0 added in v0.4.26

func Error0(err error) (e error)

func ErrorData

func ErrorData(err error) (list []string, keyValues map[string]string)

error116.ErrorData get possible string values associated with an error chain. list is a list of string values that were stored with an empty key, oldest first. keyValues are string values associated with a key string, newest key wins. err can be nil

func ErrorList

func ErrorList(err error) (errs []error)

ErrorList returns all error instances from a possible error chain. — If err is nil an empty slice is returned. — If err does not have associated errors, a slice of err, length 1, is returned. — otherwise, the first error of the returned slice is err followed by

	other errors oldest first.
- Cyclic error values are dropped

func Errorf

func Errorf(format string, a ...interface{}) (err error)

error116.Errorf is similar to fmt.Errorf but ensures that the returned err has at least one stack trace associated

func ErrorfPF added in v0.4.26

func ErrorfPF(format string, a ...interface{}) (err error)

func Errp

func Errp(errp *error) func(e error)

error116.Errp returns a function that updates an an error pointer value with additional associated errors on subsequent invocations. It is intended to be used with parl.Recover(). for a thread-safe version, use error116.ParlError

func ErrpString added in v0.4.29

func ErrpString(errp *error) (s string)

func HasStack

func HasStack(err error) (hasStack bool)

HasStack detects if the error chain already contains a stack trace

func InvokeIfError added in v0.4.26

func InvokeIfError(errp *error, errFn func(err error))

func Is added in v0.4.26

func Is(errp *error, format string, a ...interface{}) (isBad bool)

Is returns true if *errp contains a non-nil error

  • if return value is true and format is not empty string, *errp is updated with fmt.Errorf using format and a, typically including “%w” and an error
  • if *errp is non-nil and does not have a stack, a stack is inserted into its error chain
  • errp cannot be nil or panic

func Is2 added in v0.4.26

func Is2(errp *error, e error, format string, a ...interface{}) (isBad bool)

func Is2PF added in v0.4.26

func Is2PF(errp *error, e error, format string, a ...interface{}) (isBad bool)

func IsError added in v0.4.9

func IsError[T error](err T) (isError bool)

IsError determines if err represents error condition for all error implementations

  • eg. unix.Errno that is uintptr

func IsPF added in v0.4.26

func IsPF(errp *error, format string, a ...interface{}) (isBad bool)

func IsPanic added in v0.4.26

func IsPanic(err error) (isPanic bool, stack pruntime.StackSlice, recoveryIndex, panicIndex int)

IsPanic determines if err is the result of a panic. Thread-safe

  • isPanic is true if a panic was detected in the inner-most stack trace of err’s error chain
  • err must have stack trace from perrors.ErrorfPF perrors.Stackn or similar function
  • stack[recoveryIndex] is the code line of the deferred function containing recovery invocation
  • stack[panicIndex] is the code line causing the panic
  • perrors.Short displays the error message along with the code location raising panic
  • perrors.Long displays all available information about the error

func IsType added in v0.4.9

func IsType(err error, pointerToErrorValue interface{}) (hadErrpType bool)

IsType determines if the chain of err contains an error of type target. IsType is different from errors.Is in that IsType matches the type of err, not its value. IsType is different from errors.Is in that it works for error implementations missing the Is() method. IsType uses reflection. pointerToErrorValue argument is a pointer to an error implementation value, ie:

if the target struct has pointer reciever, the argument type *targetStruct
if the target struct has value receiver, the argument type targetStruct

func IsWarning

func IsWarning(err error) (isWarning bool)

IsWarning determines if an error has been flagged as a warning.

func Long

func Long(err error) string

error116.Long() gets a comprehensive string representation similar to printf %+v and LongFormat. ShortFormat does not print stack traces, data and associated errors. Long() prints full stack traces, string key-value and list values for both the error chain of err, and associated errors and their chains

error-message
  github.com/haraldrudell/parl/error116.(*csTypeName).FuncName
    /opt/sw/privates/parl/error116/chainstring_test.go:26
  runtime.goexit
    /opt/homebrew/Cellar/go/1.17.8/libexec/src/runtime/asm_arm64.s:1133

func New

func New(s string) error

error116.New is similar to errors.New but ensures that the returned error has at least one stack trace associated

func NewPF added in v0.4.26

func NewPF(s string) error

func PackFunc

func PackFunc() (packageDotFunction string)

error116.PackFunc returns the package name and function name of the caller:

error116.FuncName

func PackFuncN added in v0.4.26

func PackFuncN(skipFrames int) (packageDotFunction string)

func Short

func Short(err error) string

perrors.Short gets a one-line location string similar to printf %-v and ShortFormat. Short() does not print stack traces, data and associated errors. Short() does print a one-liner of the error message and a brief code location:

error-message at error116.(*csTypeName).FuncName-chainstring_test.go:26

func Stack

func Stack(err error) (err2 error)

error116.Stack ensures the err has a stack trace associated. err can be nil in which nil is returned

func Stackn

func Stackn(err error, framesToSkip int) (err2 error)

error116.Stackn always attaches a new stack trace to err and allows for skipping stack frames using framesToSkip. if err is nil, no action is taken

func TagErr added in v0.4.26

func TagErr(e error, tags ...string) (err error)

func Warning

func Warning(err error) error

error116.Warning indicates that err is a problem of less severity than error. It is uesed for errors that are not to terminate the thread. A Warning can be detected using error116.IsWarning().

Types

type ParlError

type ParlError struct {
	errorglue.SendNb // non-blocking channel for sending errors Send() Shutdown()
	// contains filtered or unexported fields
}

ParlError is a thread-safe error container that can optionally send errors non-blocking on a channel. ParlError is a 2018 construct and is deprecated in favor of parl.NBChan[error]. NBChan is both a channel and a store, providing the consumer additional freedoms.

func NewParlError

func NewParlError(errCh chan error) (pe *ParlError)

NewParlError provides a thread-safe error container that can optionally send incoming errors non-blocking on a channel.

If a channel is not used, a zero-value works:

var err error116.ParlError
…
return err

When using a channel, The error channel is closed by Shutdown():

errCh := make(chan error)
err := NewParlError(errCh)
…
err.Shutdown()
…
if err, ok := <- errCh; !ok {
  // errs was shutdown

A shutdown ParlError is still usable, but will no longer send errors

func (*ParlError) AddError

func (pe *ParlError) AddError(err error) (err1 error)

AddError stores additional errors in the container. Thread-safe. Returns the current state. For a non-thread-safe version, use error116.Errp

func (*ParlError) AddErrorProc

func (pe *ParlError) AddErrorProc(err error)

AddErrorProc stores additional errors in the container It is thread-safe and has a no-return-value signature. For a non-thread-safe version, use error116.Errp

func (*ParlError) Error

func (pe *ParlError) Error() string

Error() makes ParlError behave like an error. Error is thread-safe unlike in most other Error implementations. Because code will check if ParlError is nil, which it mostly isn’t, and then invoke .Error(), it may be that Error is invoked when the error field is nil. For those situations, return “<nil>” like fmt.Print might do

func (*ParlError) GetError

func (pe *ParlError) GetError() (err error)

GetError returns the error value enclosed in ParlError. Thread-safe

func (*ParlError) InvokeIfError added in v0.4.15

func (pe *ParlError) InvokeIfError(fn func(err error))

InvokeIfError invokes fn if the error store contains an error

type SupportsIs added in v0.4.86

type SupportsIs interface {
	error
	Is(target error) (isThisType bool)
}

SupportsIs is used for type assertions determining if an error value implements the Is() method, therefore supports errors.Is()

Jump to

Keyboard shortcuts

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