Skip to content

Commit f31dbaa

Browse files
committed
完成了第一小节的一部分
1 parent 04b02e5 commit f31dbaa

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

11.1.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,37 @@ Go语言设计的时候主要的特点是:简洁、明白,简洁是指语法
1212

1313
其实这样的error返回在Go语言的很多内置包里面有很多,我们这个小节将详细的介绍这些error是怎么设计的,以及在我们设计的Web应用如何更好的处理error。
1414
## Error类型
15-
error类型是一个接口类型,这是他的定义
15+
error类型是一个接口类型,这是它的定义
1616

1717
type error interface {
1818
Error() string
1919
}
2020

21+
error是一个内置的类型变量,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的非导出结构errorString
22+
23+
// errorString is a trivial implementation of error.
24+
type errorString struct {
25+
s string
26+
}
27+
28+
func (e *errorString) Error() string {
29+
return e.s
30+
}
31+
你可以通过`errors.New`把一个字符串转化为errorString,然后返回error接口,其内部实现如下:
32+
33+
// New returns an error that formats as the given text.
34+
func New(text string) error {
35+
return &errorString{text}
36+
}
37+
38+
下面这个例子演示了如何使用`errors.New`:
39+
40+
func Sqrt(f float64) (float64, error) {
41+
if f < 0 {
42+
return 0, errors.New("math: square root of negative number")
43+
}
44+
// implementation
45+
}
2146

2247
## 自定义Error
2348

0 commit comments

Comments
 (0)