diff --git a/11.1.md b/11.1.md index f068429e..b71cbc5b 100644 --- a/11.1.md +++ b/11.1.md @@ -12,12 +12,37 @@ Go语言设计的时候主要的特点是:简洁、明白,简洁是指语法 其实这样的error返回在Go语言的很多内置包里面有很多,我们这个小节将详细的介绍这些error是怎么设计的,以及在我们设计的Web应用如何更好的处理error。 ## Error类型 -error类型是一个接口类型,这是他的定义: +error类型是一个接口类型,这是它的定义: type error interface { Error() string } +error是一个内置的类型变量,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的非导出结构errorString + + // errorString is a trivial implementation of error. + type errorString struct { + s string + } + + func (e *errorString) Error() string { + return e.s + } +你可以通过`errors.New`把一个字符串转化为errorString,然后返回error接口,其内部实现如下: + + // New returns an error that formats as the given text. + func New(text string) error { + return &errorString{text} + } + +下面这个例子演示了如何使用`errors.New`: + + func Sqrt(f float64) (float64, error) { + if f < 0 { + return 0, errors.New("math: square root of negative number") + } + // implementation + } ## 自定义Error