In this post, we will learn how to perform basic error handling in Golang.

Error handling in Golang is somewhat unconventional when compared to other programming languages such as Java or Python. However, after the initial criticism it received, people have come to appreciate the error handling approach in Golang.

If you are new to Golang, I will recommend you to start with Golang Hello World and also Calling External Golang Functions post. We will be using examples from these posts to understand the error handling aspects.

1 – What is an Error?

An error is nothing but unwanted and unusual conditions that occur in a program. Errors can occur during compile time or run time. For example, accessing a file that does not exist can cause error. A failed DB connection can cause an error. Even calling another function with incorrect input can lead to an error situation.

Error Handling is about dealing with these error situations and giving an appropriate response to the end-user. This is quite similar to try-catch blocks in Java or Python.

However, Golang follows a different approach than normal try-catch blocks.

2 – The Error Interface

Golang represents errors using the built-in error type.

type error interface {  
    Error() string
}

The interface contains a single method. Basically, this method returns an error message as string. Any type that implements the error interface can also be used as an error.

When we use fmt.Println() to print the error, Golang automatically calls the Error() method that returns the error message. We will see it in action soon.

3 – Return an Error

Golang’s philosophy about error handling is quite straightforward.

Don’t ignore errors.

In other words, Golang expects the developers to account for the various errors that can occur. See below example of our greeting function that returns a greeting based on the input name.

package greeting

import (
	"errors"
	"fmt"
)

func HelloGreeting(name string) (string, error) {

	if name == "" {
		return "", errors.New("Empty Name Received as Input. Please correct")
	}

	message := fmt.Sprintf("Hello %v", name)
	return message, nil
}

Notice the function definition. Instead of returning just a string, we are also returning an error. In Golang, it is possible for functions to return more than 1 object.

The errors.New() function helps us create an error message. Basically, we check whether the input name is valid. You can check out the documentation of errors package here.

If not valid, we return an empty greeting message and an appropriate error message. If valid, we return the greeting message and the error as nil. Here, nil is a special keyword that means no error.

4 – Error Handling

Now that we have successfully returned an error, we need to handle it in the calling function.

See below example:

package main

import (
	"fmt"
	"log"

	"progressivecoder.com/greeting"
)

func main() {
	log.SetPrefix("Greeting Generator:")
	log.SetFlags(0)

	message, err := greeting.HelloGreeting("")

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(message)
}

Here, we use the log package to log the error. While calling the function greeting.HelloGreeting, we pass a blank string as input. Also, we expect it to return a message and error type.

Next, we simply check if err is not nil. If true, we terminate the program by using log.Fatal() function. If the err is nil, we simply print the greeting message.

The basic idea here is that if err is not nil, we need to do some appropriate error handling. In this case, we logged it and stopped the program. However, we can also retry the function or just log it and forget about it.

If we run the above program now, we would see log messages in the console and the program will exit.

Conclusion

With this, we have successfully learnt how to perform basic error handling in Golang. We used the standard error interface for the same.

There are some other nuances to error handling which we will cover in the next post about Golang Panic and Recover mechanism.

If you have any comments or queries, please feel free to mention in the comments section below.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *