1 回答

TA貢獻1993條經驗 獲得超6個贊
使用默認方法時,來自的錯誤pkg/errors不會打印堆棧,而是使用打印它。String()"%+v"
這在文檔的格式化打印錯誤部分中進行了解釋:
從這個包返回的所有錯誤值都實現了 fmt.Formatter 并且可以被 fmt 包格式化。支持以下動詞:
%s print the error. If the error has a Cause it will be
printed recursively.
%v see %s
%+v extended format. Each Frame of the error's StackTrace will
be printed in detail.
WithStack的文檔有顯示不同行為的示例:
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Println(err)
// Output:
// whoops
fmt.Printf("%+v", err)
// Output:
// whoops
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
// testing.runExample
// ...
請注意,如果您直接使用errors.New,則不需要使用WithStack,errors.New已經為您完成了,如本操場示例所示:
package main
import (
"fmt"
"github.com/pkg/errors"
)
func main() {
err := errors.New("whoops")
fmt.Printf("String: %s\n", err)
fmt.Printf("Verbose: %+v\n", err)
}
輸出:
String: whoops
Verbose: whoops
main.main
/tmp/sandbox878560423/prog.go:10
runtime.main
/usr/local/go-faketime/src/runtime/proc.go:204
runtime.goexit
/usr/local/go-faketime/src/runtime/asm_amd64.s:1374
- 1 回答
- 0 關注
- 204 瀏覽
添加回答
舉報