返回並處理錯誤
處理錯誤是編寫健壯程式碼的關鍵功能。在本節中,您將向 greetings 模組新增一些程式碼來返回錯誤,然後在呼叫方中處理它。
- 在 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
(表示沒有錯誤)作為第二個值。這樣,呼叫方就可以知道函式已成功執行。
- 修改函式,使其返回兩個值:一個
- 在您的 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) }
在此程式碼中,您
- 在
hello
目錄的命令列中,執行 hello.go 以確認程式碼正常工作。現在您傳遞了一個空名稱,您將收到一個錯誤。
$ go run . greetings: empty name exit status 1
這就是 Go 中常見的錯誤處理方式:將錯誤作為值返回,以便呼叫方可以檢查它。
接下來,您將使用 Go slice 返回一個隨機選擇的問候語。