Learning Go from Documentation #3 (Error handling)

Kuzey Köse
2 min readDec 24, 2021

This blog is about returning and handling an error. Handling errors is an essential topic. We created two simple modules in Learning Go from Documentation #2 (Call your code from another module). We are continuing with a created folder in the #2 blog.

We have a greetings folder. Inside of this folder, we have a greeting.go file. We need to change the greetings.go file.

// 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
}

Importing errors package is essential here. This is because errors can be usable like errors.New(”empty name”). In the Hello function, the control of the name is provided is empty or not. Then return empty string and error. Your caller will check the second value to see if an error occurred. Also, adding nil (meaning no error) to the second return shows a successful return.

Any Go function can return multiple values.

Let’s move on to the hello folder, hello.go file. Now, we handle the error that returns by the Hello function.

// hello.go
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
log.SetPrefix("greetings: ")
log.SetFlags(0)
message, err := greetings.Hello("") // error hendling
if err != nil {
log.Fatal(err)
}
fmt.Println(message)
}

Configure the log package to print “greetings:” at the start with a log.SetPrefix(”greetings:”). Assign two returning parameters to message and err. For testing errors, let’s put the empty string in the Hello function. Then the condition part comes, if the error is not nil then log the error with log.Fatal(err). If it’s nil, code continues with ftm.Println(message).

Open the terminal and run what we write;

// terminal$ go run .
greetings: empty name
exit status 1

This blog post is personal notes 🙂 If you are more interested in it, you need to check https://go.dev/doc/tutorial/handle-errors site.

--

--