type error interface {
Error() string
}
生成一個新的error並返回
一般有以下幾種處理方式:
package main
import (
"errors"
"fmt"
)
type Customerror struct {
infoa string
infob string
Err 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 error
the error test for fmt.Errorf
infoa : 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.EOF
var EOF = errors.New("EOF")
//net.Error
type Error interface {
error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}