_content/doc/tutorial/handle-errors.html
Handling errors is an essential feature of solid code. In this section, you'll add a bit of code to return an error from the greetings module, then handle it in the caller.
There's no sense sending a greeting back if you don't know who to greet. Return an error to the caller if the name is empty. Copy the following code into greetings.go and save the file.
In your hello/hello.go file, handle the error now returned by the Hello function, along with the non-error value.
Paste the following code into 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)
}
In this code, you:
log package to print the command name ("greetings: ") at the start of its log messages, without a time stamp or source file information.Hello return values, including the error, to variables.Hello argument from Gladys’s name to an empty string, so you can try out your error-handling code.error value. There's no sense continuing in this case.log package to output error information. If you get an error, you use the log package's Fatal function to print the error and stop the program.hello directory, run hello.go to confirm that the code works.Now that you're passing in an empty name, you'll get an error.
$ go run .
greetings: empty name
exit status 1
That's common error handling in Go: Return an error as a value so the caller can check for it.
Next, you'll use a Go slice to return a randomly-selected greeting.
< Call your code from another moduleReturn a random greeting >