Goerror实践1.Go原生error2.Err

1. Go原生error

Go原生的error是一个接口类型,只要实现Error()方法就是一个error

type error interface {
	Error() string
}
复制代码

一般我们使用errors.New()来生成一个error,注意这个方法返回的每个error都是不同的,即使表示错误的字符串是完全相同的,因为这个方法返回的是error对象指针

// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
	return &errorString{text}//这里有个知识点,就是结构体初始化的三种方式与异同,可以参考[Ref 1](#Ref)
}

// errorString is a trivial implementation of error.
type errorString struct {
	s string
}

func (e *errorString) Error() string {
	return e.s
}
复制代码

2. Error和Exception

Go中不存在Exception,而是支持多参数返回中包含Error。通过多参数和简单的约定,Go让程序员知道了什么时候出现了问题,并通过保留panic来反馈真正的异常。

defer 与 recovery()

Ref

  1. Go 结构体与初始化
  2. Go语言数据类型
  3. golang panic和recover 实现原理