返回及處理異常

處理錯誤是可靠程式碼的一個基本特性。在本節中,您將新增一些程式碼以從問候語模組返回錯誤,然後在呼叫者中處理它。

In greetings/greetings。go, add the code highlighted below。

在檔案greetings/greetings。go中,修改為以下程式碼,增加引入errors,以及error的處理。

如果你不知道該向誰打招呼,那麼回送問候是沒有意義的。如果名稱為空,則向呼叫方返回錯誤。將以下程式碼複製到greetings。go並儲存檔案。

packagegreetings

import(

“errors”

“fmt”

//Helloreturnsagreetingforthenamedperson。

funcHello(namestring) (string,error) {

//Ifnonamewasgiven,returnanerrorwithamessage。

ifname==“”{

return“”,errors。New(“empty name”)

}

//Ifanamewasreceived,returnavaluethatembedsthename

//inagreetingmessage。

message:=fmt。Sprintf(“Hi, %v。 Welcome!”,name)

returnmessage,nil

}

在這個程式碼裡:

Change the function so that it returns two values: aand an。 Your caller will check the second value to see if an error occurred。 (Any Go function can return multiple values。 For more, seeEffective Go。)

修改該函式使得它返回兩個值:string和error。呼叫者將需要檢查第二個值判斷是否發生了錯誤。(所有的Go 函式都可以返回多個值)。

Import the Go standard librarypackage so you can use its

引入Go標準庫errors,利用這個庫可以使用它的function。

新增‘if’語句以檢查無效請求(名稱應為空字串),如果請求無效,則返回錯誤。函式返回一個包含訊息的。

在成功返回中新增“nil”(意味著沒有錯誤)作為第二個值。這樣,呼叫方就可以看到函式成功了。

In your hello/hello。go file, handle the error now returned by the

在hello/hello。go檔案中,處理現在返回的error資訊。

將下面程式碼複製至改檔案:

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)

}

在這個程式碼裡:

Configure thepackageto print the command name (“greetings: ”) at the start of its log messages, without a time stamp or source file information。

Assign both of thereturn values, including the, to variables。

Change theargument from Gladys’s name to an empty string, so you can try out your error-handling code。

Look for a non-nilvalue。 There‘s no sense continuing in this case。

Use the functions in the standard library’sto output error information。 If you get an error, you use thepackage‘sfunctionto print the error and stop the program。

配置包在其日誌訊息的開頭列印命令名(“greetings:”),而不帶時間戳或原始檔資訊。

為變數分配兩個“Hello”返回值,包括“error”。

將’Hello‘引數從Gladys的名稱更改為空字串,以便可以嘗試錯誤處理程式碼。

查詢非nil值。在這種情況下繼續下去是沒有意義的。

使用標準庫的“日誌包”中的函式輸出錯誤資訊。如果出現錯誤,則使用’log‘包的’Fatal‘函式列印錯誤並停止程式。

At the command line in the

執行hello程式,在該目錄下執行go run 。

現在我們輸入空姓名則返回error。

$ go run 。

greetings: empty name

exit status 1

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

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