go 自定义error
|
字数总计:
1136
|
阅读时长:
0分钟
|
阅读量:
552
这篇文章距离最后更新已过45 天,如果文章内容或图片资源失效,请留言反馈,我会及时处理,谢谢!
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 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