From 54941d0a33ade50a0f80df0b594a083ed976563a Mon Sep 17 00:00:00 2001 From: xiemengjun Date: Wed, 31 Oct 2012 23:12:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BA=86=E7=AC=AC=E4=B8=80?= =?UTF-8?q?=E5=B0=8F=E8=8A=82=E7=9A=84=E4=B8=80=E9=83=A8=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 11.1.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) 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