version: 1.9.2

package errors

import "errors"

概述

errors 包实现了关于错误处理的函数。

例:

  1. package errors_test
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // MyError 实现了 error interface,包含一个时间和信息字段。
  7. type MyError struct {
  8. When time.Time
  9. What string
  10. }
  11. func (e MyError) Error() string {
  12. return fmt.Sprintf("%v: %v", e.When, e.What)
  13. }
  14. func oops() error {
  15. return MyError{
  16. time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
  17. "the file system has gone away",
  18. }
  19. }
  20. func Example() {
  21. if err := oops(); err != nil {
  22. fmt.Println(err)
  23. }
  24. // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
  25. }

索引

例子

文件

errors.go

func New

  1. func New(text string) error

New 方法返回一个以给定文本格式化的 error 对象。

例:

  1. err := errors.New("emit macho dwarf: elf header corrupted")
  2. if err != nil {
  3. fmt.Print(err)
  4. }
  5. // Output: emit macho dwarf: elf header corrupted

例:

  1. const name, id = "bimmler", 17
  2. err := fmt.Errorf("user %q (id %d) not found", name, id)
  3. if err != nil {
  4. fmt.Print(err)
  5. }
  6. // Output: user "bimmler" (id 17) not found