错误处理
var errNotFound error = errors.New("Not found error") func main() { fmt.Printf("error: %v", errNotFound) }
上面的error类型其实是一个接口
我们可以实现它的Error()方法继承这个接口,自定义错误类型
import ( "fmt" "os" "time" ) type PathError struct { path string op string message string createTime string } func (p *PathError) Error() string { return fmt.Sprint("path=%s, createTime=%s, op=%s, message=%s", p.path, p.createTime, p.op, 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.Sprint("%v", time.Now()), } } defer file.Close() return nil } func main() { err := Open("C://dsfsfkjsdjfds.txt") v, ok := err.(*PathError) // 断言进行类型判断,查看是否是自己定义的类型 if ok { fmt.Println("get path err", v) } }