建立自定義錯誤型別

在 Go 中,錯誤由可以將自身描述為字串的任何值表示。任何實現內建 error 介面的型別都是錯誤的。

// The error interface is represented by a single
// Error() method, that returns a string representation of the error
type error interface {
    Error() string
}

以下示例顯示如何使用字串複合文字定義新的錯誤型別。

// Define AuthorizationError as composite literal
type AuthorizationError string

// Implement the error interface
// In this case, I simply return the underlying string
func (e AuthorizationError) Error() string {
    return string(e)
}

我現在可以使用我的自定義錯誤型別作為錯誤:

package main

import (
    "fmt"
)

// Define AuthorizationError as composite literal
type AuthorizationError string

// Implement the error interface
// In this case, I simply return the underlying string
func (e AuthorizationError) Error() string {
    return string(e)
}

func main() {
    fmt.Println(DoSomething(1)) // succeeds! returns nil
    fmt.Println(DoSomething(2)) // returns an error message
}

func DoSomething(someID int) error {
    if someID != 1 {
        return AuthorizationError("Action not allowed!")
    }

    // do something here

    // return a nil error if the execution succeeded
    return nil
}