Skip to content
This repository has been archived by the owner on Dec 1, 2021. It is now read-only.

#75 Wrap() add withStack only if no cause with stack present #122

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ type fundamental struct {
*stack
}

func (f *fundamental) hasStack() bool { return true }

func (f *fundamental) Error() string { return f.msg }

func (f *fundamental) Format(s fmt.State, verb rune) {
Expand Down Expand Up @@ -174,13 +176,24 @@ func (w *withStack) Format(s fmt.State, verb rune) {
}
}

func (w *withStack) hasStack() bool { return true }

// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
type hasStacker interface {
hasStack() bool
}
if err == nil {
return nil
}
if stacker, ok := err.(hasStacker); ok && stacker.hasStack() {
return &withMessage{
cause: err,
msg: message,
}
}
err = &withMessage{
cause: err,
msg: message,
Expand All @@ -195,9 +208,18 @@ func Wrap(err error, message string) error {
// at the point Wrapf is call, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
type hasStacker interface {
hasStack() bool
}
if err == nil {
return nil
}
if stacker, ok := err.(hasStacker); ok && stacker.hasStack() {
return &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
}
err = &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
Expand Down Expand Up @@ -242,6 +264,16 @@ func (w *withMessage) Format(s fmt.State, verb rune) {
}
}

func (w *withMessage) hasStack() bool {
type hasStacker interface {
hasStack() bool
}
if cause, ok := w.Cause().(hasStacker); ok {
return cause.hasStack()
}
return false
}

// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
Expand Down