這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
Golang中的error類型
error類型本身就是一個預定義好的介面,裡面定義了一個method
type error interface { Error() string}
產生一個新的error並返回
一般有以下幾種處理方式:
package mainimport ("errors""fmt")type Customerror struct {infoa stringinfob stringErr error}func (cerr Customerror) Error() string {errorinfo := fmt.Sprintf("infoa : %s , infob : %s , original err info : %s ", cerr.infoa, cerr.infob, cerr.Err.Error())return errorinfo}func main() {//方法一://採用errors包的New方法 返回一個err的類型var err error = errors.New("this is a new error")//由於已經實現了error介面的方法 因此可以直接調用對應的方法fmt.Println(err.Error())//方法二://採用fmt.Errof 將string資訊轉化為error資訊 並返回err = fmt.Errorf("%s", "the error test for fmt.Errorf")fmt.Println(err.Error())//方法三://採用自訂的方式實現一個error的 一個duck 類型err = &Customerror{infoa: "err info a",infob: "err info b",Err: errors.New("test custom err"),}fmt.Println(err.Error())}/*output:this is a new errorthe error test for fmt.Errorfinfoa : err info a , infob : err info b , original err info : test custom err */
golang中的 error package 內容也比較簡單,這個package中實現了error中所聲明的method(Error)相當於是一個error介面的duck類型。
// Package errors implements functions to manipulate errors.package errors// New returns an error that formats as the given text.func New(text string) error {return &errorString{text}}// errorString is a trivial implementation of error.type errorString struct {s string}func (e *errorString) Error() string {return e.s}
採用fmt.Errorf方法把string類型轉化為error類型,在這個方法的內部,先調用fmt包中的Sprintf方法把格式化的輸入轉化為字串,在使用 errors.New 方法返回error類型。
採用自訂的error類型可以先判斷err的動態類型,再進行下一層的判斷。
比如net.Error介面,是一個對原先error介面的再封裝。在讀取檔案的時候判斷讀取器讀取結束的時候的io.EOF。
//io.EOFvar EOF = errors.New("EOF")//net.Error type Error interface {errorTimeout() bool // Is the error a timeout?Temporary() bool // Is the error temporary?}