Don't just check errors, handle them gracefully (2016)

https://news.ycombinator.com/rss Hits: 3
Summary

This post is an extract from my presentation at the recent GoCon spring conference in Tokyo, Japan. Errors are just values I’ve spent a lot of time thinking about the best way to handle errors in Go programs. I really wanted there to be a single way to do error handling, something that we could teach all Go programmers by rote, just as we might teach mathematics, or the alphabet. However, I have concluded that there is no single way to handle errors. Instead, I believe Go’s error handling can be classified into the three core strategies. Sentinel errors The first category of error handling is what I call sentinel errors. if err == ErrSomething { … } The name descends from the practice in computer programming of using a specific value to signify that no further processing is possible. So to with Go, we use specific values to signify an error. Examples include values like io.EOF or low level errors like the constants in the syscall package, like syscall.ENOENT. There are even sentinel errors that signify that an error did not occur, like go/build.NoGoError, and path/filepath.SkipDir from path/filepath.Walk. Using sentinel values is the least flexible error handling strategy, as the caller must compare the result to predeclared value using the equality operator. This presents a problem when you want to provide more context, as returning a different error would will break the equality check. Even something as well meaning as using fmt.Errorf to add some context to the error will defeat the caller’s equality test. Instead the caller will be forced to look at the output of the error‘s Error method to see if it matches a specific string. Never inspect the output of error.Error As an aside, I believe you should never inspect the output of the error.Error method. The Error method on the error interface exists for humans, not code. The contents of that string belong in a log file, or displayed on screen. You shouldn’t try to change the behaviour of your program by inspecting ...

First seen: 2025-06-03 19:42

Last seen: 2025-06-03 21:42