Golang中的error類型

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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?}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.