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类型是一个接口类型,这是它的定义:
1818 Error() string
1919 }
2020
21- error是一个内置的类型变量 ,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的私有结构errorString
21+ error是一个内置的接口类型 ,我们可以在/builtin/包下面找到相应的定义。而我们在很多内部包里面用到的 error是errors包下面的实现的私有结构errorString
2222
2323 // errorString is a trivial implementation of error.
2424 type errorString struct {
@@ -28,6 +28,7 @@ error是一个内置的类型变量,我们可以在/builtin/包下面找到相
2828 func (e *errorString) Error() string {
2929 return e.s
3030 }
31+
3132你可以通过` errors.New ` 把一个字符串转化为errorString,以得到一个满足接口error的对象,其内部实现如下:
3233
3334 // New returns an error that formats as the given text.
@@ -71,6 +72,18 @@ Offset字段在调用Error的时候不会被打印,但是我们可以通过类
7172 return err
7273 }
7374
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+
7487上面例子简单的演示了如何自定义Error类型。但是如果我们还需要更复杂的错误处理呢?此时,我们来参考一下net包采用的方法:
7588
7689 package net
Original file line number Diff line number Diff line change @@ -246,4 +246,4 @@ GDB的一些常用命令如下所示
246246## links
247247 * [ 目录] ( < preface.md > )
248248 * 上一节: [ 错误处理] ( < 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