errs

package module
v0.0.0-...-6b122da Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2023 License: MIT Imports: 10 Imported by: 16

README

go-errs

Go 1.13 compatible error wrapping with call stacks and function parameters

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var TrimFilePathPrefix = filePathPrefix()

TrimFilePathPrefix will be trimmed from the beginning of every call-stack file-path. Defaults to $GOPATH/src/ of the build environment or will be empty if go build gets called with -trimpath.

Functions

func As

func As[T error](err error) []T

As returns all errors of type T in the wrapping tree of err.

This function is similar to errors.As but traverses the full tree using the interface methods:

Unwrap() error
Unwrap() []error

func AsError

func AsError(val any) error

AsError converts any type to an error without wrapping it. Nil values will be converted to a nil error.

func AsErrorWithDebugStack

func AsErrorWithDebugStack(val any) error

AsErrorWithDebugStack converts any type to an error and if not nil wraps it with debug.Stack() after a newline. Nil values will be converted to a nil error.

func DontLog

func DontLog(err error) error

DontLog wraps the passed error as LogDecisionMaker so that ShouldLog returns false. A nil error won't be wrapped but returned as nil.

func Errorf

func Errorf(format string, a ...any) error

Errorf wraps the result of fmt.Errorf with the current call stack.

If the format specifier includes a %w verb with an error operand, the returned error will implement an Unwrap method returning the operand. It is invalid to include more than one %w verb or to supply it with an operand that does not implement the error interface. The %w verb is otherwise a synonym for %v.

func FormatFunctionCall

func FormatFunctionCall(function string, params ...any) string

FormatFunctionCall formats a function call in pseudo syntax using github.com/domonda/go-pretty to format the params. Used to format errors with function call stack information.

func Has

func Has[T error](err error) bool

Has is a shortcut for errors.As when the target error value is not needed.

func IsContextCanceled

func IsContextCanceled(ctx context.Context) bool

IsContextCanceled checks if the context Done channel is closed and if the context error unwraps to context.Canceled.

func IsContextDeadlineExceeded

func IsContextDeadlineExceeded(ctx context.Context) bool

IsContextDeadlineExceeded checks if the context Done channel is closed and if the context error unwraps to context.DeadlineExceeded.

func IsContextDone

func IsContextDone(ctx context.Context) bool

IsContextDone checks if the context Done channel is closed.

func IsContextError

func IsContextError(err error) bool

IsContextError returns true if err unwraps to context.Canceled or context.DeadlineExceeded.

func IsErrNotFound

func IsErrNotFound(err error) bool

IsErrNotFound returns true if the passed error unwraps to, or is ErrNotFound, sql.ErrNoRows, or os.ErrNotExist.

func IsOtherThanErrNotFound

func IsOtherThanErrNotFound(err error) bool

IsOtherThanErrNotFound returns true if the passed error is not nil and does not unwrap to, or is ErrNotFound, sql.ErrNoRows, or os.ErrNotExist.

func IsType

func IsType(err, ref error) bool

IsType returns if err or any unwrapped error is of the type of the passed ref error. It works similar than errors.As but without assigning to the ref error and without checking for Is or As methods.

func LogFunctionCall

func LogFunctionCall(logger Logger, function string, params ...any)

LogFunctionCall using FormatFunctionCall if logger is not nil

func LogPanicWithFuncParams

func LogPanicWithFuncParams(log Logger, params ...any)

LogPanicWithFuncParams recovers any panic, converts it to an error wrapped with the callstack of the panic and the passed function parameter values and prints it with the prefix "LogPanicWithFuncParams: " to the passed Logger. After logging, the original panic is re-paniced.

func New

func New(text string) error

New returns a new error with the passed text wrapped with the current call stack.

func RecoverAndLogPanicWithFuncParams

func RecoverAndLogPanicWithFuncParams(log Logger, params ...any)

RecoverAndLogPanicWithFuncParams recovers any panic, converts it to an error wrapped with the callstack of the panic and the passed function parameter values and prints it with the prefix "RecoverAndLogPanicWithFuncParams: " to the passed Logger.

func RecoverPanicAsError

func RecoverPanicAsError(result *error)

RecoverPanicAsError recovers any panic, converts it to an error wrapped with the callstack of the panic and assigns it to the result error.

func RecoverPanicAsErrorWithFuncParams

func RecoverPanicAsErrorWithFuncParams(result *error, params ...any)

RecoverPanicAsErrorWithFuncParams recovers any panic, converts it to an error wrapped with the callstack of the panic and the passed function parameter values and assigns it to the result error.

func ReplaceErrNotFound

func ReplaceErrNotFound(err, replacement error) error

ReplaceErrNotFound returns the passed replacement error if IsErrNotFound(err) returns true, meaning that all (optionally wrapped) ErrNotFound, sql.ErrNoRows, os.ErrNotExist errors get replaced.

func Root

func Root(err error) error

Root unwraps err recursively and returns the root error.

func ShouldLog

func ShouldLog(err error) bool

ShouldLog checks if the passed error unwraps as a LogDecisionMaker and returns the result of its ShouldLog method. If error does not unwrap to LogDecisionMaker and is not nil then ShouldLog returns true. A nil error results in false.

func Type

func Type[T error](err error) bool

Type indicates if err is not nil and it or any unwrapped error is of the type T. It works similar than errors.As but without assigning to the ref error and without checking for Is or As methods.

func UnwrapCallStack

func UnwrapCallStack(err error) error

UnwrapCallStack unwraps callstack information from err and returns the first non callstack wrapper error. It does not remove callstack wrapping further down the wrapping chain if the top error is not wrapped with callstack information.

func WrapWith0FuncParams

func WrapWith0FuncParams(resultVar *error)

func WrapWith10FuncParams

func WrapWith10FuncParams(resultVar *error, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 any)

func WrapWith1FuncParam

func WrapWith1FuncParam(resultVar *error, p0 any)

func WrapWith2FuncParams

func WrapWith2FuncParams(resultVar *error, p0, p1 any)

func WrapWith3FuncParams

func WrapWith3FuncParams(resultVar *error, p0, p1, p2 any)

func WrapWith4FuncParams

func WrapWith4FuncParams(resultVar *error, p0, p1, p2, p3 any)

func WrapWith5FuncParams

func WrapWith5FuncParams(resultVar *error, p0, p1, p2, p3, p4 any)

func WrapWith6FuncParams

func WrapWith6FuncParams(resultVar *error, p0, p1, p2, p3, p4, p5 any)

func WrapWith7FuncParams

func WrapWith7FuncParams(resultVar *error, p0, p1, p2, p3, p4, p5, p6 any)

func WrapWith8FuncParams

func WrapWith8FuncParams(resultVar *error, p0, p1, p2, p3, p4, p5, p6, p7 any)

func WrapWith9FuncParams

func WrapWith9FuncParams(resultVar *error, p0, p1, p2, p3, p4, p5, p6, p7, p8 any)

func WrapWithCallStack

func WrapWithCallStack(err error) error

WrapWithCallStack wraps an error with the current call stack.

func WrapWithCallStackSkip

func WrapWithCallStackSkip(skip int, err error) error

WrapWithCallStackSkip wraps an error with the current call stack skipping skip stack frames.

func WrapWithFuncParams

func WrapWithFuncParams(resultVar *error, params ...any)
Example
package main

import (
	"context"
	"fmt"
)

type strct struct {
	A int
}

func funcA(ctx context.Context, i int, s string, strct *strct) (err error) {
	defer WrapWith4FuncParams(&err, ctx, i, s, strct)

	return funcB(s, "X\nX")
}

func funcB(s ...string) (err error) {
	defer WrapWithFuncParams(&err, s)

	return funcC()
}

func funcC() (err error) {
	defer WrapWithFuncParams(&err)

	return New("error in funcC")
}

func main() {
	err := funcA(context.Background(), 666, "Hello World!", &strct{A: -1})
	fmt.Println(err)

}
Output:

error in funcC
github.com/domonda/go-errs.funcC()
    github.com/domonda/go-errs/wrapwithfuncparams_test.go:27
github.com/domonda/go-errs.funcB([`Hello World!`,`X\nX`])
    github.com/domonda/go-errs/wrapwithfuncparams_test.go:21
github.com/domonda/go-errs.funcA(Context{}, 666, `Hello World!`, strct{A:-1})
    github.com/domonda/go-errs/wrapwithfuncparams_test.go:15

func WrapWithFuncParamsSkip

func WrapWithFuncParamsSkip(skip int, resultVar *error, params ...any)

Types

type LogDecisionMaker

type LogDecisionMaker interface {
	error

	// ShouldLog decides if the error should be logged
	ShouldLog() bool
}

LogDecisionMaker can be implemented by errors to decide if they should be logged. Use the package function ShouldLog to check if a wrapped error implements the interface and get the result of its ShouldLog method.

type Logger

type Logger interface {
	Printf(format string, args ...any)
}

Logger is an interface that can be implemented to log errors

type Sentinel

type Sentinel string

Sentinel implements the error interface for a string and is meant to be used to declare const sentinel errors.

Example:

const ErrUserNotFound errs.Sentinel = "user not found"
Example
const ErrUserAlreadyExists Sentinel = "user already exists"

var err error = ErrUserAlreadyExists
fmt.Println("const Sentinel errors.Is:", errors.Is(err, ErrUserAlreadyExists))

err = fmt.Errorf("%w: user@example.com", ErrUserAlreadyExists)
fmt.Println("Wrapped Sentinel errors.Is:", errors.Is(err, ErrUserAlreadyExists))
Output:

const Sentinel errors.Is: true
Wrapped Sentinel errors.Is: true
const ErrNotFound Sentinel = "not found"

ErrNotFound is an universal error returned in case that a requested resource could not be found.

Recommended usage:

This error can be returned directly from a function if that function only requests one kind of resource and no further differentiation is needed about what resource could not be found.

Else create custom "not found" error by wrapping ErrNotFound or implementing a custom error type with an

Is(target error) bool

method that returns true for target == ErrNotFound.

For checking errors it is recommended to use IsErrNotFound(err) instead of errors.Is(err, ErrNotFound) to also catch the standard library "not found" errors sql.ErrNoRows and os.ErrNotExist.

func (Sentinel) Error

func (s Sentinel) Error() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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