Skip to content

Commit fc6e4ce

Browse files
lysucoocood
authored andcommitted
fix suspend with cause bug (#16)
1 parent d95478c commit fc6e4ce

File tree

2 files changed

+38
-4
lines changed

2 files changed

+38
-4
lines changed

juju_adaptor.go

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,18 +66,37 @@ func NewNoStackError(msg string) error {
6666
}
6767
}
6868

69-
// SuspendStack suspends stack for a exists error.
70-
// it can be used to suspend follow up Trace do not add stack.
69+
// SuspendStack suspends stack generate for error.
7170
func SuspendStack(err error) error {
7271
if err == nil {
7372
return err
7473
}
75-
return withStack{
74+
cleared := clearStack(err)
75+
if cleared {
76+
return err
77+
}
78+
return &withStack{
7679
err,
7780
&emptyStack,
7881
}
7982
}
8083

84+
func clearStack(err error) (cleared bool) {
85+
switch typedErr := err.(type) {
86+
case *withMessage:
87+
return clearStack(typedErr.Cause())
88+
case *fundamental:
89+
typedErr.stack = &emptyStack
90+
return true
91+
case *withStack:
92+
typedErr.stack = &emptyStack
93+
clearStack(typedErr.Cause())
94+
return true
95+
default:
96+
return false
97+
}
98+
}
99+
81100
// ErrorStack will format a stack trace if it is available, otherwise it will be Error()
82101
// If the error is nil, the empty string is returned
83102
// Note that this just calls fmt.Sprintf("%+v", err)

stack_test.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,12 +299,27 @@ func TestNewNoStackError(t *testing.T) {
299299
}
300300
}
301301

302-
func TestSuspendStackError(t *testing.T) {
302+
func TestSuspendError(t *testing.T) {
303303
err := io.EOF
304304
err = SuspendStack(err)
305305
err = Trace(err)
306306
result := fmt.Sprintf("%+v", err)
307307
if result != "EOF" {
308308
t.Errorf("NewNoStackError(): want %s, got %v", "EOF", result)
309309
}
310+
if io.EOF != Cause(err) {
311+
t.Errorf("SuspendStackError can not got back origion error.")
312+
}
313+
}
314+
315+
func TestSuspendTracedWithMessageError(t *testing.T) {
316+
tracedErr := Trace(io.EOF)
317+
tracedErr = WithStack(tracedErr)
318+
tracedErr = WithMessage(tracedErr, "1")
319+
tracedErr = SuspendStack(tracedErr)
320+
tracedErr = Trace(tracedErr)
321+
result := fmt.Sprintf("%+v", tracedErr)
322+
if result != "EOF\n1" {
323+
t.Errorf("NewNoStackError(): want %s, got %v", "EOF\n1", result)
324+
}
310325
}

0 commit comments

Comments
 (0)