One of the more useful features of the Go programming language is the way that it handles errors. Instead of using a Try/Catch methodology like other programming languages, Go treats errors as normal return values.
By creating simple modules and applying a few logging rules, we can produce useful error messages to catch all sorts of exceptions during the development process.
In this article, we will cover some of the most basic ways Golang finds and handles these exceptions.
Golang Basic Error Handling
We can capture errors in Go by using simple if/then statements that check for conditions where required parameters are not met.
Let’s look at a basic module that we can create to check whether a string includes a value or not.
Create a package named “hello” and import the standard “errors” and “fmt” modules to recognize errors and formatted text:
package hello
import (
"errors"
"fmt"
)
Then we can create a module that will return a string of text for a named variable.
func Hello(name string) (string, error) {
if name == "" {
return "", errors.New("No name was given")
}
The above checks to see whether a blank string is returned for the “name” variable, which then returns a new error with some specified text. This is our error condition. An error condition checks to see whether the error itself exists.
If the condition is not met (i.e., there is no error), we return the value that matches the specified “name” variable:
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message, nil
}
Note that it returns the message and the value of “nil,” meaning that there is no error. This tells the calling program that the function processed with no error.
Now we will look at how we can call this package in an actual script.
Let’s create a new script, called test.go
As is normal with Golang, a script must begin with defining the package as “main.” We then import the “fmt” and “log” packages, along with our created “hello” package, as shown below:
package main
import (
"fmt"
"log"
"yoursite.com/hello"
)
Below we define our main function, set a few properties for our logger to create an easy to understand prefix, and (for security reasons) create a flag so that we don’t show the time, source file, and line number.
func main() {
log.SetPrefix("Hello: ")
log.SetFlags(0)
Next, we’ll specify a message to be displayed:
<code class="language-go">message, err := hello.Hello("")</code>
Finally, we look to see whether there is an error by checking if “err” is not equal to “nil.” If this is the case, we print the message to the console and exit.
if err != nil {
log.Fatal(err)
}
If no error condition exists, we simply print the message that was defined in our hello package.
fmt.Println(message)
}
To test this out, we can run the code as it is. Once we do, we should get a result that looks like this:
>go run test.go
greetings: No name was given
exit status 1
If we wish to modify our test.go script, enter something like this:
<code class="language-go">message, err := hello.Hello("John")</code>
Our output should then look like this:
>go run test.go
Hi, John. Welcome!
Another type of error message that we can return is:
fmt.Errorf – this will format a string according to Printf’s rules.
Handling Integers in Golang
Of course, string errors are only one type of error. With Golang error handling, there are several other errors you can check for in your code. One in particular you should know about is numerical errors.
Handling integers is simple for Go. Here’s how it works:
Say we have numerical errors, like if we were to divide by zero. First we create a “Division” function, which divides two variables x by y. For the first part of our if/then condition, we need to make sure y is not equal to zero:
func Division(x int, y int) (int, error) {
if y == 0 {
return 0, errors.New("Thou shalt not divide by zero!")
} else {
return (x / y), nil
}
}
This is the main function. Now, you can pass it two variables. In this example, we’ll use 12 and 0.
func main() {
if result, err := Division(12, 0); err != nil {
fmt.Println("We got an error: ", err)
} else {
fmt.Println("The answer is", result)
}
}
You’ll then receive a message that says something like:
“We got an error: Thou shalt not divide by zero!”
This is just one example of how you can use Golang error handling to find numerical errors. Really, with the right functions, you can find several errors on your own via Golang.
Finding HTTP Status Errors
With Golang, you can bring up HTTP status errors if an API we are calling delivers one.
Here’s how:
First, let’s import a new package, “net/http”:
import (
"fmt"
"log"
"net/http"
)
In our main function, call an app (e.g. a website) and log any errors. We know that successful requests fall within the 2xx range, so create a respective status that finds any HTTP errors that fall outside this range. You can do this in the following way:
func main() {
resp, err := http.Get("https://example.com")
if err != nil {
log.Fatal(err)
}fmt.Println("HTTP Response Status:", resp.StatusCode,
http.StatusText(resp.StatusCode))
if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
fmt.Println("This is a successful request")
} else {
fmt.Println("Non-OK HTTP status:", response.StatusCode)
}
}
As you can see, our main function is set to
>= 200 && resp.StatusCode <= 299
which will check to see if any HTTP requests fall within the 2xx range. If the request does not meet this condition, it will show an error message.
With only one module, you can quickly gather all the information you need to find and fix your Golang code.
Summary
This guide only scratches the surface as to how the Go language is designed to handle errors. However, basics such as how to check for the existence of a string, how to raise an error condition if an illogical numerical statement is presented, and how to check the HTTP status codes of a response are all great places to start on your Golang error monitoring journey.
Don’t have time to check and use these Golang error handling techniques manually? That’s where tools like Airbrake Error Monitoring come in handy. With Airbrake Error Monitoring, you’ll be able to find errors quickly without the need to create individual modules. Try Airbrake Error Monitoring free for 30 days for unlimited errors and performance events.