傳回並處理錯誤
處理錯誤是穩固程式碼的基本功能。在本節中,您將新增一些程式碼來傳回 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 }
在此程式碼中,您
-
變更函式,使其傳回兩個值:一個
字串
和一個錯誤
。您的呼叫者會檢查第二個值,以查看是否發生錯誤。(任何 Go 函式都可以傳回多個值。如需更多資訊,請參閱 Effective Go。) -
匯入 Go 標準函式庫
errors
套件,以便您可以使用其errors.New
函式。 -
新增一個
if
陳述式,以檢查無效的請求(名稱應該為空字串)並在請求無效時傳回錯誤。errors.New
函式會傳回一個錯誤
,其中包含您的訊息。 -
在成功的傳回中,新增
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 切片傳回一個隨機選擇的問候語。