File tree Expand file tree Collapse file tree 2 files changed +15
-2
lines changed Expand file tree Collapse file tree 2 files changed +15
-2
lines changed Original file line number Diff line number Diff line change @@ -18,7 +18,7 @@ error类型是一个接口类型,这是它的定义:
18
18
Error() string
19
19
}
20
20
21
- error是一个内置的类型变量 ,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的私有结构errorString
21
+ error是一个内置的接口类型 ,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的私有结构errorString
22
22
23
23
// errorString is a trivial implementation of error.
24
24
type errorString struct {
@@ -28,6 +28,7 @@ error是一个内置的类型变量,我们可以在/builtin/包下面找到相
28
28
func (e *errorString) Error() string {
29
29
return e.s
30
30
}
31
+
31
32
你可以通过` errors.New ` 把一个字符串转化为errorString,以得到一个满足接口error的对象,其内部实现如下:
32
33
33
34
// New returns an error that formats as the given text.
@@ -71,6 +72,18 @@ Offset字段在调用Error的时候不会被打印,但是我们可以通过类
71
72
return err
72
73
}
73
74
75
+ 需要注意的是,函数返回自定义错误时,返回值也应设置为error类型,而非自定义错误类型,也不应预声明自定义错误类型的变量。例如:
76
+
77
+ func Decode() *SyntaxError { // 错误,将可能导致上层调用者err!=nil的判断永远为true。
78
+ var err *SyntaxError // 预声明错误变量
79
+ if 出错条件 {
80
+ err = &SyntaxError{}
81
+ }
82
+ return err // 错误,虽然err变量等于nil,但仍可能导致上层调用者err!=nil的判断为true
83
+ }
84
+
85
+ 原因见 http://golang.org/doc/faq#nil_error
86
+
74
87
上面例子简单的演示了如何自定义Error类型。但是如果我们还需要更复杂的错误处理呢?此时,我们来参考一下net包采用的方法:
75
88
76
89
package net
Original file line number Diff line number Diff line change @@ -246,4 +246,4 @@ GDB的一些常用命令如下所示
246
246
## links
247
247
* [ 目录] ( < preface.md > )
248
248
* 上一节: [ 错误处理] ( < 11.1.md > )
249
- * 下一节: [ Go怎么写测试用例] ( < 11.3.md > )
249
+ * 下一节: [ Go怎么写测试用例] ( < 11.3.md > )
You can’t perform that action at this time.
0 commit comments