akavel's digital garden

The missing guide to errors in Go

Among people writing in the Go programming language, it is a common complaint to claim that the language needs sprinkling the codebase with “if err != nil { return err }” blocks. As far as I understand the intention of the authors of the Go language, this is a misguided conclusion. Even more than that—to my understanding, such blocks are in fact an antipattern.

Go is indeed constructed in a way that generally makes it necessary to write “if err != nilconditionals, this part is true. But the subtle—yet extremely important—difference is in how the body of those blocks is intended to look. Their whole purpose is to make it as easy as possible for a deliberate Go programmer to add valuable context to error messages.

In shortest words, an ideal, idiomatic block of error-passing Go code could be summarized as:

if err != nil {
	return fmt.Errorf("<describing uniquely local context>: %w", err)
}

Notably, such an error message should describe the context as completely as is possible and useful for a caller, but as minimally as is possible from the side of the callee. In other words: a function should responsibly describe valuable information that it uniquely knows, while assuming and trusting the same high bar of responsibility from the callee (thus, not trying to patronisingly steal that responsibility from them).

![To be continued…]

🌱 seedling — contents of this article got classified among young, unrefined ideas that I’ve just planted—or old, unrefined ideas that need watering. If I am a diligent, caring gardener, they’ll grow into budding and maybe even ripe.
© Mateusz Czapliński 🐘 Mastodon 🐙 GitHub 🎮 Itch.io ♟️ BGG 🧶 Ravelry