error 包

Golang 使用 error 类型返回函数执行中遇到的错误

nil表示未遇到错误,否则会返回字符串说明返回的错误信息

  • error 只是一个接口 可以使用任意类型去实现
type error interface {
    Error() interface
}
  • error 不一定代表错误

    • io 包内的 error 类型 io.EOF 代表数据读取结束
    • path/filepath包内 error 类型的 filepath.SkipDir 表示跳过当前目录
  • errors包实现最简单的 error 类型 只包含字符串

    • func New(text string) error New 函数生成简单的 error 对象
  • 可自定义 error 类型

    type myError struct {
        err string
        time time.Time
        count int
    }
    func (m *myError)Error() string {
        return fmt.Sprintf("%s %d count, time is %v", m.err,m.count,m.time)
    } 
    func newError (s string , i int) {
        return &myError{
            err:s,
            time:time.Now(),
            count:i,
        }
    }