Skip to content

Commit

Permalink
Add docs and a few helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg committed Jun 2, 2023
1 parent 8c3642f commit 101b81f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
20 changes: 20 additions & 0 deletions errorx.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import (
"strings"
)

// Newf returns an error according to a format specifier and param.
// Each call to New returns a distinct error value even if the text is identical.
//
// If tracing is enabled then stacktrace is attached to the returned error.
func Newf(format string, a ...any) error {
// NOTE: go vet printf check doesn't understand inverse expression.
if !IsTracingEnabled() || strings.Contains(format, "%w") {
Expand All @@ -32,11 +36,19 @@ func As(err error, target any) bool {
return errors.As(err, target)
}

// Into is type-safe alternative to [errorx.As].
func Into[T error](err error) (T, bool) {
var dst T
ok := As(err, &dst)
return dst, ok
}

// Unwrap is just [errors.Unwrap].
func Unwrap(err error) error {
return errors.Unwrap(err)
}

// IsAny is just a multiple [errors.Is] calls.
func IsAny(err, target error, targets ...error) bool {
if errors.Is(err, target) {
return true
Expand All @@ -50,6 +62,14 @@ func IsAny(err, target error, targets ...error) bool {
return false
}

// Must returns value or panic if the error is non-nil.
func Must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}

// errorString same as [errors.errorString] but with a frame field.
type errorString struct {
s string
Expand Down
3 changes: 3 additions & 0 deletions frame.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ func (f Frame) Format(p Printer) {
}
}

// Caller returns a Frame that describes a frame on the caller's stack.
// The argument skip is the number of frames to skip over.
// Caller(0) returns the frame for the caller of Caller.
func caller(skip int) Frame {
var s Frame
runtime.Callers(skip+1, s.frames[:])
Expand Down

0 comments on commit 101b81f

Please sign in to comment.