gopl-zh.github.com/ch7/ch7-08.md

76 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 7.8. error接口
從本書的開始我們就已經創建和使用過神祕的預定義error類型而且沒有解釋它究竟是什麽。實際上它就是interface類型這個類型有一個返迴錯誤信息的單一方法
```go
type error interface {
Error() string
}
```
創建一個error最簡單的方法就是調用errors.New函數它會根據傳入的錯誤信息返迴一個新的error。整個errors包僅隻有4行
```go
package errors
func New(text string) error { return &errorString{text} }
type errorString struct { text string }
func (e *errorString) Error() string { return e.text }
```
承載errorString的類型是一個結構體而非一個字符串這是爲了保護它表示的錯誤避免粗心或有意的更新。併且因爲是指針類型*errorString滿足error接口而非errorString類型所以每個New函數的調用都分配了一個獨特的和其他錯誤不相同的實例。我們也不想要重要的error例如io.EOF和一個剛好有相同錯誤消息的error比較後相等。
```go
fmt.Println(errors.New("EOF") == errors.New("EOF")) // "false"
```
調用errors.New函數是非常稀少的因爲有一個方便的封裝函數fmt.Errorf它還會處理字符串格式化。我們曾多次在第5章中用到它。
```go
package fmt
import "errors"
func Errorf(format string, args ...interface{}) error {
return errors.New(Sprintf(format, args...))
}
```
雖然*errorString可能是最簡單的錯誤類型但遠非隻有它一個。例如syscall包提供了Go語言底層繫統調用API。在多個平台上它定義一個實現error接口的數字類型Errno併且在Unix平台上Errno的Error方法會從一個字符串表中査找錯誤消息如下面展示的這樣
```go
package syscall
type Errno uintptr // operating system error code
var errors = [...]string{
1: "operation not permitted", // EPERM
2: "no such file or directory", // ENOENT
3: "no such process", // ESRCH
// ...
}
func (e Errno) Error() string {
if 0 <= int(e) && int(e) < len(errors) {
return errors[e]
}
return fmt.Sprintf("errno %d", e)
}
```
下面的語句創建了一個持有Errno值爲2的接口值表示POSIX ENOENT狀況
```go
var err error = syscall.Errno(2)
fmt.Println(err.Error()) // "no such file or directory"
fmt.Println(err) // "no such file or directory"
```
err的值圖形化的呈現在圖7.6中。
![](../images/ch7-06.png)
Errno是一個繫統調用錯誤的高效表示方式它通過一個有限的集合進行描述併且它滿足標準的錯誤接口。我們會在第7.11節了解到其它滿足這個接口的類型。