Go Wiki: 錯誤

錯誤是透過將 error 作為函式的附加返回值來指示的。nil 值表示沒有錯誤。

可以透過呼叫 error(它們唯一的函式)將其轉換為字串。你可以透過呼叫 errors.New 來從字串建立錯誤

if failure {
    return errors.New("inverse tachyon pulse failed")
}

或使用 fmt.Errorf

if failure {
    return fmt.Errorf("inverse tachyon pulse failed")
}

錯誤字串不應以大寫字母開頭,因為列印時它們通常會被新增字首。

err := TryInverseTachyonPulse()
if err != nil {
    fmt.Printf("failed to solve problem: %s\n", err)
}

如果你希望呼叫程式碼能夠處理錯誤,你可以透過返回特殊值或新型別來區分錯誤類別。你只需要區分呼叫程式碼可能需要以這種方式處理的差異,因為字串允許傳達錯誤的詳細資訊。

io.EOF 是一個表示流結束的特殊值。你可以直接將錯誤值與 io.EOF 進行比較。

如果你想攜帶錯誤的額外資料,你可以使用新型別。

type ParseError struct {
    Line, Col int
}

func (p ParseError) Error() string {
    return fmt.Sprintf("parse error on line %d, column %d", p.Line, p.Col)
}

如果你想建立一個常量字串錯誤,你可以使用命名型別字串。

type errorConst string

const ErrTooManyErrors errorConst = "too many errors found."

func (e errorConst) Error() string {
    return string(e)
}

呼叫程式碼會使用型別開關來測試一種特殊的 error 型別。

switch err := err.(type) {
case ParseError:
    PrintParseError(err)
}

命名

錯誤型別以 "Error" 結尾,錯誤變數以 "Err""err" 開頭。

package somepkg

// ParseError is type of error returned when there's a parsing problem.
type ParseError struct {
  Line, Col int
}

var ErrBadAction = errors.New("somepkg: a bad action was performed")

// -----

package foo

func foo() {
    res, err := somepkgAction()
    if err != nil {
        if err == somepkg.ErrBadAction {
        }
        if pe, ok := err.(*somepkg.ParseError); ok {
             line, col := pe.Line, pe.Col
             // ....
        }
    }
}

參考


此內容是 Go Wiki 的一部分。