Pocket Gophers

Error Checking While Prototyping

You don't seem to check for errors in your restore and save calls. How do you know that your save is actually working? 

Please check your errors if you depend on the call's success!

The reason that I didn't do it, is because I don't know how to do it.

"check your errors" is not just a basic advice, it's a MUST!

I see this sort of conversation all the time. This time on golang-nuts. Error checking is hard and can be distracting when you are just trying to figure out how some code should work. Not checking your errors frustrates when the code isn't working; you think it should, but it doesn't; you finally add error checking; and the error tells you exactly what went wrong.

What if you could just focus on your prototype or proof of concept?

When prototyping, I use a simple method that helps me check all of my errors while not allowing those checks to distract me from figuring out my code. It consists of two parts: log.SetFlags(log.Lshortfile), and log.Fatalln(err)

First, put log.SetFlags(log.Lshortfile) as the first line of your main():

package main

import "log"

func main() {

This tells the log package to print the file name and line number where your specific log.Fatalln(err) occurs:

main.go:8: error string
exit status 1

Without this setting you get the less useful:

2016/11/01 09:16:51 error string
exit status 1

Second, after every error that is returned (and assigned to err), write:

if err != nil {

Now you don’t have to think about the errors because, by default, you always handle them the same way.

When a particular error needs more context, I can usually get away with just appending variables: log.Fatalln(err, var1, var2). This is usually good enough because it is like writing log.Fatalf("%v %v %v", err, var1, var2) without having to manage the format string.

When you discover an error that needs to be handled without your prototype terminating, such as dealing with io.EOF, implement appropriate error handling.

Don’t use this method in production.

Your production code should (probably) not have log.Fatal. This means you can easily check if any of your prototype error handling made it into production by searching for log.Fatal.

Dig into the Fundamentals of Go

Subscribe to receive a weekly email covering a Go fundamental. Be it the language, its tooling, or its packages, you will learn what you need to know.