type error interface {
Error() string
}
内建error接口 类型用于表示错误信息,nil值表示无错误, 不属于哪一个包, 能直接使用
errors包中的New函数可以构建error变量
func main() {
var err = errors.New(" has error")
fmt.Println(err.Error())
}
fmt包中有一个函数Errorf可以格式化, 也返回error
func main() {
path := "xxx"
err := fmt.Errorf("path = %s is error", path)
fmt.Printf(err.Error())
}
error是一个接口, 如果想要自定义错误, 也可以实现此接口
// 定义一个结构体, 用于实现error接口
type PathError struct {
Path string
Date string
Operator string
Message string
}
// 实现error接口的方法
func (pe *PathError) Error() string {
return fmt.Sprintf("path = %s, date = %s, operator = %s, message = %s", pe.Path, pe.Date, pe.Operator, pe.Message)
}
// 打开文件函数, 返回error, 如果实现了它, 则可返回其实现
func OpenFile(path string) error {
file, err := os.Open(path)
if err != nil {
return &PathError { // 如果打开文件失败, 则我返回自定义的 PathError
Path : path,
Date : fmt.Sprintf("%v", time.Now()),
Operator : "open",
Message : err.Error(),
}
}
defer file.Close()
return nil
}
func main() {
var filePath = "xxxx"
err := OpenFile(filePath)
switch v := err.(type) {
case *PathError :
fmt.Printf("%v", v.Error())
}
}
panic 和 recover
func badCall() {
panic("...") // 让程序panic
}
func test() {
defer func() {
if e:= recover(); e != nil { // 接收panic信息
fmt.Printf("panicing%s\n", e)
}
}()
badCall()
fmt.Printf("end \n")
}
func main() {
test()
}