Go語言入門到入土——三、處理并返回異常
文章目錄
- Go語言入門到入土——三、處理并返回異常
- 1. 在greetings.go中添加異常處理代碼
- 2. 在hello.go中添加日志記錄代碼
- 3. 運行
1. 在greetings.go中添加異常處理代碼
處理空輸入的異常,代碼如下:
package greetingsimport ("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
}
2. 在hello.go中添加日志記錄代碼
記錄空異常的日志代碼如下:
package mainimport ("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)
}
3. 運行
go run main.go
結果如下:
greetings: empty name
exit status 1