package main import ( "fmt" "os" "time" ) type PathError struct { path string op string creatTime string message string } func (p *PathError) Error() string { return fmt.Sprintf("path=%s \nop=%s \ncreateTime=%s \nmessage=%s", p.path, p.op, p.creatTime, p.message) } func Open(fileName string) error { file, err := os.Open(fileName) if err != nil { return &PathError{ path: fileName, op: "read", message: err.Error(), creatTime: fmt.Sprintf("%v", time.Now()), } } defer file.Close() return nil } func main() { err := Open("/gocode/github.com/passwd01/studygo/golang/test.txt") switch v := err.(type) { case *PathError: fmt.Println("get path error,", v) default: } }
GO
╰ go run main.go -╯
get path error, path=/gocode/github.com/passwd01/studygo/golang/test.txt
op=read
createTime=2022-09-14 15:13:27.80366 +0800 CST m=+0.000191561
message=open /gocode/github.com/passwd01/studygo/golang/test.txt: no such file or directory
Bash