add Wrap(), Base(), HasTrace()
This commit is contained in:
parent
a8fd5b2cbd
commit
825e9a1235
1 changed files with 32 additions and 7 deletions
39
errors.go
39
errors.go
|
@ -1,11 +1,17 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
base "errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-errors/errors"
|
||||
)
|
||||
|
||||
// interop with pkg/errors
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
|
||||
// Err intelligently creates/handles errors, while preserving the stack trace.
|
||||
// It works with errors from github.com/pkg/errors too.
|
||||
func Err(err interface{}, fmtParams ...interface{}) error {
|
||||
|
@ -13,10 +19,6 @@ func Err(err interface{}, fmtParams ...interface{}) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
|
||||
if _, ok := err.(causer); ok {
|
||||
err = fmt.Errorf("%+v", err)
|
||||
} else if errString, ok := err.(string); ok && len(fmtParams) > 0 {
|
||||
|
@ -26,6 +28,19 @@ func Err(err interface{}, fmtParams ...interface{}) error {
|
|||
return errors.Wrap(err, 1)
|
||||
}
|
||||
|
||||
// Wrap calls errors.Wrap, in case you want to skip a different amount
|
||||
func Wrap(err interface{}, skip int) *errors.Error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, ok := err.(causer); ok {
|
||||
err = fmt.Errorf("%+v", err)
|
||||
}
|
||||
|
||||
return errors.Wrap(err, skip+1)
|
||||
}
|
||||
|
||||
// Is compares two wrapped errors to determine if the underlying errors are the same
|
||||
func Is(e error, original error) bool {
|
||||
return errors.Is(e, original)
|
||||
|
@ -44,14 +59,24 @@ func Trace(err error) string {
|
|||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return string(errors.Wrap(Err(err), 0).Stack())
|
||||
return string(Err(err).(*errors.Error).Stack())
|
||||
}
|
||||
|
||||
|
||||
// FullTrace returns the error type, message, and stack trace
|
||||
func FullTrace(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return errors.Wrap(Err(err), 0).ErrorStack()
|
||||
return Err(err).(*errors.Error).ErrorStack()
|
||||
}
|
||||
|
||||
// Base returns a simple error with no stack trace attached
|
||||
func Base(text string) error {
|
||||
return base.New(text)
|
||||
}
|
||||
|
||||
// HasTrace checks if error has a trace attached
|
||||
func HasTrace(err error) bool {
|
||||
_, ok := err.(*errors.Error)
|
||||
return ok
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue