Skip to content

Commit

Permalink
fix suspend with cause bug (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
lysu authored and coocood committed May 15, 2019
1 parent d95478c commit fc6e4ce
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
25 changes: 22 additions & 3 deletions juju_adaptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,37 @@ func NewNoStackError(msg string) error {
}
}

// SuspendStack suspends stack for a exists error.
// it can be used to suspend follow up Trace do not add stack.
// SuspendStack suspends stack generate for error.
func SuspendStack(err error) error {
if err == nil {
return err
}
return withStack{
cleared := clearStack(err)
if cleared {
return err
}
return &withStack{
err,
&emptyStack,
}
}

func clearStack(err error) (cleared bool) {
switch typedErr := err.(type) {
case *withMessage:
return clearStack(typedErr.Cause())
case *fundamental:
typedErr.stack = &emptyStack
return true
case *withStack:
typedErr.stack = &emptyStack
clearStack(typedErr.Cause())
return true
default:
return false
}
}

// ErrorStack will format a stack trace if it is available, otherwise it will be Error()
// If the error is nil, the empty string is returned
// Note that this just calls fmt.Sprintf("%+v", err)
Expand Down
17 changes: 16 additions & 1 deletion stack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,12 +299,27 @@ func TestNewNoStackError(t *testing.T) {
}
}

func TestSuspendStackError(t *testing.T) {
func TestSuspendError(t *testing.T) {
err := io.EOF
err = SuspendStack(err)
err = Trace(err)
result := fmt.Sprintf("%+v", err)
if result != "EOF" {
t.Errorf("NewNoStackError(): want %s, got %v", "EOF", result)
}
if io.EOF != Cause(err) {
t.Errorf("SuspendStackError can not got back origion error.")
}
}

func TestSuspendTracedWithMessageError(t *testing.T) {
tracedErr := Trace(io.EOF)
tracedErr = WithStack(tracedErr)
tracedErr = WithMessage(tracedErr, "1")
tracedErr = SuspendStack(tracedErr)
tracedErr = Trace(tracedErr)
result := fmt.Sprintf("%+v", tracedErr)
if result != "EOF\n1" {
t.Errorf("NewNoStackError(): want %s, got %v", "EOF\n1", result)
}
}

0 comments on commit fc6e4ce

Please sign in to comment.