xerror

package
v2.3.4 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: MIT Imports: 9 Imported by: 2

Documentation

Overview

Package xerror implements helpers for errors

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func TryUnwrap added in v2.1.15

func TryUnwrap[T any](val T, err error) T

TryUnwrap if err is nil then it returns a valid value If err is not nil, Unwrap panics with err. Play: https://go.dev/play/p/w84d7Mb3Afk

Example
result1 := TryUnwrap(strconv.Atoi("42"))
fmt.Println(result1)

_, err := strconv.Atoi("4o2")
defer func() {
	v := recover()
	result2 := reflect.DeepEqual(err.Error(), v.(*strconv.NumError).Error())
	fmt.Println(result2)
}()

TryUnwrap(strconv.Atoi("4o2"))
Output:

42
true

Types

type CatchError added in v2.3.4

type CatchError struct {
	Msg   string
	File  string
	Line  int
	Cause error
}

CatchError is an error type to handle try-catch-finally block.

func WrapCatchError added in v2.3.4

func WrapCatchError(err error, msg string) *CatchError

WrapCatchError wraps an error with message, file, and line.

func (*CatchError) Error added in v2.3.4

func (e *CatchError) Error() string

Error returns the error message.

type Stack added in v2.1.15

type Stack struct {
	Func string `json:"func"`
	File string `json:"file"`
	Line int    `json:"line"`
}

Stack contains function, file and line number info in the stack trace.

type StackTrace added in v2.1.15

type StackTrace []frame

StackTrace is array of frame. It's exported for compatibility with github.com/pkg/errors

func (StackTrace) Format added in v2.1.15

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

type TryCatch added in v2.3.4

type TryCatch struct {
	// contains filtered or unexported fields
}

TryCatch is a struct to handle try-catch-finally block. This implementation is merely a simulation of Java-style try-catch and does not align with Go's error-handling philosophy. It is recommended to use it with caution.

Example
calledFinally := false
calledCatch := false

tc := NewTryCatch(context.Background())

tc.Try(func(ctx context.Context) error {
	return errors.New("error message")
}).Catch(func(ctx context.Context, err error) {
	calledCatch = true
	// Error in try block at /path/xxx.go:174 - Cause: error message
	// fmt.Println(err.Error())
}).Finally(func(ctx context.Context) {
	calledFinally = true
}).Do()

fmt.Println(calledCatch)
fmt.Println(calledFinally)
Output:

true
true

func NewTryCatch added in v2.3.4

func NewTryCatch(ctx context.Context) *TryCatch

NewTryCatch creates a new TryCatch instance.

func (*TryCatch) Catch added in v2.3.4

func (tc *TryCatch) Catch(catchFunc func(ctx context.Context, err error)) *TryCatch

Catch sets the catch function.

func (*TryCatch) Do added in v2.3.4

func (tc *TryCatch) Do()

Do executes the try-catch-finally block.

func (*TryCatch) Finally added in v2.3.4

func (tc *TryCatch) Finally(finallyFunc func(ctx context.Context)) *TryCatch

Finally sets the finally function.

func (*TryCatch) Try added in v2.3.4

func (tc *TryCatch) Try(tryFunc func(ctx context.Context) error) *TryCatch

Try sets the try function.

type XError added in v2.1.15

type XError struct {
	// contains filtered or unexported fields
}

XError is to handle error related information.

func New added in v2.1.15

func New(format string, args ...any) *XError

New creates a new XError with message

Example
err := New("error")
fmt.Println(err.Error())
Output:

error

func Unwrap

func Unwrap(err error) *XError

Unwrap returns unwrapped XError from err by errors.As. If no XError, returns nil

func Wrap added in v2.1.15

func Wrap(cause error, message ...any) *XError

Wrap creates a new XError and add message.

Example
err := New("wrong password")
wrapErr := Wrap(err, "error")

fmt.Println(wrapErr.Error())
Output:

error: wrong password

func (*XError) Error added in v2.1.15

func (e *XError) Error() string

Error implements standard error interface.

func (*XError) Format added in v2.1.15

func (e *XError) Format(s fmt.State, verb rune)

Format returns: - %v, %s, %q: formatted message - %+v: formatted message with stack trace

func (*XError) Id added in v2.1.15

func (e *XError) Id(id string) *XError

Id sets id to check equality in XError.Is

Example
err1 := New("error").Id("e001")
err2 := New("error").Id("e001")
err3 := New("error").Id("e003")

equal := err1.Is(err2)
notEqual := err1.Is(err3)

fmt.Println(equal)
fmt.Println(notEqual)
Output:

true
false

func (*XError) Info added in v2.1.15

func (e *XError) Info() *errInfo

Info returns information of xerror, which can be printed.

Example
cause := errors.New("error")
err := Wrap(cause, "invalid username").Id("e001").With("level", "high")

errInfo := err.Info()

fmt.Println(errInfo.Id)
fmt.Println(errInfo.Cause)
fmt.Println(errInfo.Values["level"])
fmt.Println(errInfo.Message)
Output:

e001
error
high
invalid username

func (*XError) Is added in v2.1.15

func (e *XError) Is(target error) bool

Is checks if target error is XError and Error.id of two errors are matched.

Example
err1 := New("error").Id("e001")
err2 := New("error").Id("e001")
err3 := New("error").Id("e003")

equal := err1.Is(err2)
notEqual := err1.Is(err3)

fmt.Println(equal)
fmt.Println(notEqual)
Output:

true
false

func (*XError) StackTrace added in v2.1.15

func (e *XError) StackTrace() StackTrace

StackTrace returns stack trace which is compatible with pkg/errors

Example
err := New("error")

stacks := err.Stacks()

fmt.Println(stacks[0].Func)
fmt.Println(stacks[0].Line)

containFile := strings.Contains(stacks[0].File, "xerror_example_test.go")
fmt.Println(containFile)
Output:

github.com/duke-git/lancet/v2/xerror.ExampleXError_StackTrace
53
true

func (*XError) Stacks added in v2.1.15

func (e *XError) Stacks() []*Stack

Stacks returns stack trace array generated by pkg/errors

func (*XError) Unwrap added in v2.1.15

func (e *XError) Unwrap() error

Unwrap compatible with github.com/pkg/errors

Example
err1 := New("error").With("level", "high")
err2 := err1.Wrap(errors.New("invalid username"))

err := err2.Unwrap()

fmt.Println(err.Error())
Output:

invalid username

func (*XError) Values added in v2.1.15

func (e *XError) Values() map[string]any

Values returns map of key and value that is set by With. All wrapped xerror.XError key and values will be merged. Key and values of wrapped error is overwritten by upper xerror.XError.

Example
err := New("error").With("level", "high")

errLevel := err.Values()["level"]

fmt.Println(errLevel)
Output:

high

func (*XError) With added in v2.1.15

func (e *XError) With(key string, value any) *XError

With adds key and value related to the error object

Example
err := New("error").With("level", "high")

errLevel := err.Values()["level"]

fmt.Println(errLevel)
Output:

high

func (*XError) Wrap added in v2.1.15

func (e *XError) Wrap(cause error) *XError

Wrap creates a new XError and copy message and id to new one.

Example
err1 := New("error").With("level", "high")
err2 := err1.Wrap(errors.New("invalid username"))

fmt.Println(err2.Error())
Output:

error: invalid username

Jump to

Keyboard shortcuts

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