错误处理

处理错误是可靠代码的一个基本特性,在本节,你会在greeting模块中添加一小块代码 返回一个错误,然后在调用器中处理它.

1.在Ingreetings/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和一个错误.调用器将检查第二个值,用来发现是否出现错误(任何Go函数都能返回任意数量的值)
  • 引入Go标准库errors包,这样你就能在代码中使用errors.New这个函数了
  • 添加if语句,用来检查请求是否有效(名字应为空字符串),之后当请求是非法的那么就返回错误, errors.New函数在你的消息中添加一个错误.
  • 当返回是成功的,就将第二个值赋值为nil(意思是 没有错误),这样,调用器就能看到这个函数已经成功.

2.在hello/hello.go代码中,现在就要处理hello函数返回的错误和非错误了.

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包参数,以使log消息的开头打印出命令名称("greetings")
  • 将error和消息都赋值给变量
  • 将hallo入参由 Gladys's 改为 空字符串,这样你就能尝试出错误处理了
  • 查找非nil错误值。在这种情况下继续下去是没有意义的。
  • 使用标准库日志包中的函数输出错误信息。如果出现错误,可以使用日志包的Fatal函数打印错误并停止程序。

3.在hello路径下,运行 run hello.go 

$ go run .
greetings: empty name
exit status 1

这是Go中常见的错误处理:将错误作为值返回,以便调用方可以检查它。

接下来,您将使用Go片段返回随机问候语。

原文地址:https://www.cnblogs.com/yaoshi641/p/15237207.html