5.自定义error

最后更新于:2022-04-02 04:44:32

自定义error: ~~~ package main import ( "fmt" "os" "time" ) type PathError struct { path string op string createTime string message string } func (p *PathError) Error() string { return fmt.Sprintf("path=%s \nop=%s \ncreateTime=%s \nmessage=%s", p.path, p.op, p.createTime, p.message) } func Open(filename string) error { file, err := os.Open(filename) if err != nil { return &PathError{ path: filename, op: "read", message: err.Error(), createTime: fmt.Sprintf("%v", time.Now()), } } defer file.Close() return nil } func main() { err := Open("/Users/***/Desktop/go/src/test.txt") switch v := err.(type) { case *PathError: fmt.Println("get path error,", v) default: } } ~~~ 输出结果: ~~~ get path error, path=/Users/***/Desktop/go/src/test.txt op=read createTime=2018-04-05 11:25:17.331915 +0800 CST m=+0.000441790 message=open /Users/***/Desktop/go/src/test.txt: no such file or directory ~~~
';