version: 1.9.2
package errors
import "errors"
概述
errors 包实现了关于错误处理的函数。
package errors_testimport ("fmt""time")// MyError 实现了 error interface,包含一个时间和信息字段。type MyError struct {When time.TimeWhat string}func (e MyError) Error() string {return fmt.Sprintf("%v: %v", e.When, e.What)}func oops() error {return MyError{time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),"the file system has gone away",}}func Example() {if err := oops(); err != nil {fmt.Println(err)}// Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away}
索引
例子
文件
func New ¶
New 方法返回一个以给定文本格式化的 error 对象。
err := errors.New("emit macho dwarf: elf header corrupted")if err != nil {fmt.Print(err)}// Output: emit macho dwarf: elf header corrupted
const name, id = "bimmler", 17err := fmt.Errorf("user %q (id %d) not found", name, id)if err != nil {fmt.Print(err)}// Output: user "bimmler" (id 17) not found
