爲了理解go error,進一步學習github.com/pkg/errors做的訓練。html
http://www.shtml.net/article/content/tok/48369/id/37733.htmlgit
https://studygolang.com/articles/17430?fr=sidebargithub
https://blog.csdn.net/weixin_42506905/article/details/94482183golang
https://blog.csdn.net/fwhezfwhez/article/details/79175376ide
https://www.jianshu.com/p/75d3682cd135學習
package main import ( "fmt" "os" "runtime" "github.com/pkg/errors" ) func main() { content, err := openFile() if err != nil { fmt.Println(err) } else { fmt.Println(string(content)) } // github.com/pkg/errors測試 errPkg := test1() if errPkg != nil { fmt.Println("err:", errPkg) } fmt.Printf("err :%+v\n", errPkg) fmt.Println("Hello world") } type stack []uintptr type errorString struct { s string *stack } func callers() *stack { const depth = 32 var pcs [depth]uintptr n := runtime.Callers(3, pcs[:]) var st stack = pcs[0:n] return &st } func newError(text string) error { return &errorString{ s: text, stack: callers(), } } //error只有一個方法 Error,只要實現了這個方法,就是實現了error func (e *errorString) Error() string { return e.s } //只是模擬一個錯誤 func openFile() ([]byte, error) { return nil, newError("new custom error") } func test1() error { _, err := os.Open("helloworld.txt") if err != nil { //return errors.WithMessage(err, "test1") return errors.Wrap(err, "test1") } return nil }