13.0-13.10

This commit is contained in:
Unknwon
2015-11-25 01:23:32 -05:00
parent b439076d21
commit 3aa7fb8bcf
14 changed files with 54 additions and 102 deletions

View File

@@ -4,14 +4,12 @@
```go
func handler1(w http.ResponseWriter, r *http.Request) { ... }
```
假设所有的函数都有这样的签名:
```go
func f(a type1, b type2)
```
参数的数量和类型是不相关的。
@@ -20,7 +18,6 @@ func f(a type1, b type2)
```go
fType1 = func f(a type1, b type2)
```
在我们的模式中使用了两个帮助函数:
@@ -39,12 +36,11 @@ func errorHandler(fn fType1) fType1 {
defer func() {
if e, ok := recover().(error); ok {
log.Printf(run time panic: %v, err)
}
}
}()
fn(a, b)
fn(a, b)
}
}
```
当错误发生时会 recover 并打印在日志中;除了简单的打印,应用也可以用 template 包(参见 [15.7 节](15.7.md)为用户生成自定义的输出。check() 函数会在所有的被调函数中调用,像这样:
@@ -60,7 +56,6 @@ func f1(a type1, b type2) {
check(err2)
...
}
```
通过这种机制,所有的错误都会被 recover并且调用函数后的错误检查代码也被简化为调用 check(err) 即可。在这种模式下,不同的错误处理必须对应不同的函数类型;它们(错误处理)可能被隐藏在错误处理包内部。可选的更加通用的方式是用一个空接口类型的切片作为参数和返回值。
@@ -93,7 +88,7 @@ func f() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
}()
fmt.Println("Calling g.")
g(0)
fmt.Println("Returned normally from g.")
@@ -108,7 +103,11 @@ func g(i int) {
fmt.Println("Printing in g", i)
g(i + 1)
}
/* Output:
```
输出:
```
Calling g.
Printing in g 0
Printing in g 1
@@ -121,15 +120,12 @@ Defer in g 1
Defer in g 0
Recovered in f 4
Returned normally from f.
*/
```
**练习 13.3**[panic_defer_convint.go](exercises/chapter_13/panic_defer_convint.go)
写一个 ConvertInt64ToInt 函数把 int64 值转换为 int 值,如果发生错误(提示:参见 [4.5.2.1 节](04.5.md#4521-整型-int-和浮点型-float))就 panic。然后在函数 IntFromInt64 中调用这个函数并 recover返回一个整数和一个错误。请测试这个函数
## 链接
- [目录](directory.md)