返回並處理錯誤

處理錯誤是編寫健壯程式碼的關鍵功能。在本節中,您將向 greetings 模組新增一些程式碼來返回錯誤,然後在呼叫方中處理它。

  1. 在 greetings/greetings.go 中,新增下面高亮顯示的程式碼。

    如果您不知道要向誰致意,就沒有意義返回問候語。如果名稱為空,則向呼叫方返回錯誤。將以下程式碼複製到 greetings.go 並儲存檔案。

    package greetings
    
    import (
        "errors"
        "fmt"
    )
    
    // Hello returns a greeting for the named person.
    func Hello(name string) (string, error) {
        // If no name was given, return an error with a message.
        if name == "" {
            return "", errors.New("empty name")
        }
    
        // If a name was received, return a value that embeds the name
        // in a greeting message.
        message := fmt.Sprintf("Hi, %v. Welcome!", name)
        return message, nil
    }
    

    在此程式碼中,您

    • 修改函式,使其返回兩個值:一個 string 和一個 error。您的呼叫方將檢查第二個值以確定是否發生了錯誤。(任何 Go 函式都可以返回多個值。有關更多資訊,請參閱 Effective Go。)
    • 匯入 Go 標準庫 errors 包,以便您可以使用其 errors.New 函式
    • 新增一個 if 語句來檢查無效請求(在應為名稱的位置為空字串),並在請求無效時返回錯誤。errors.New 函式返回一個 error,其中包含您的訊息。
    • 在成功的返回值中新增 nil(表示沒有錯誤)作為第二個值。這樣,呼叫方就可以知道函式已成功執行。
  2. 在您的 hello/hello.go 檔案中,現在處理 Hello 函式返回的錯誤以及非錯誤值。

    將以下程式碼貼上到 hello.go 中。

    package main
    
    import (
        "fmt"
        "log"
    
        "example.com/greetings"
    )
    
    func main() {
        // Set properties of the predefined Logger, including
        // the log entry prefix and a flag to disable printing
        // the time, source file, and line number.
        log.SetPrefix("greetings: ")
        log.SetFlags(0)
    
        // Request a greeting message.
        message, err := greetings.Hello("")
        // If an error was returned, print it to the console and
        // exit the program.
        if err != nil {
            log.Fatal(err)
        }
    
        // If no error was returned, print the returned message
        // to the console.
        fmt.Println(message)
    }
    

    在此程式碼中,您

    • 配置 log,使其在日誌訊息的開頭列印命令名稱(“greetings: ”),而不帶時間戳或原始檔名資訊。
    • Hello 的兩個返回值(包括 error)都賦給變數。
    • Hello 的引數從 Gladys 的名字更改為空字串,以便您可以試用錯誤處理程式碼。
    • 查詢非 nilerror 值。在這種情況下,繼續執行沒有意義。
    • 使用標準庫 log 包中的函式輸出錯誤資訊。如果您收到錯誤,請使用 log 包的 Fatal 函式 來列印錯誤並停止程式。
  3. hello 目錄的命令列中,執行 hello.go 以確認程式碼正常工作。

    現在您傳遞了一個空名稱,您將收到一個錯誤。

    $ go run .
    greetings: empty name
    exit status 1
    

這就是 Go 中常見的錯誤處理方式:將錯誤作為值返回,以便呼叫方可以檢查它。

接下來,您將使用 Go slice 返回一個隨機選擇的問候語。