Embracing if err != nil Without Crying
Every newcomer to Go goes through the same emotional journey. First comes curiosity: "Oh, errors are just values, how neat." Then confusion: "Why does every third line say if err != nil?" Then anger, usually around the two-hundredth repetition. Then, if all goes well, acceptance, and one day you catch yourself thinking, "Huh. I actually know exactly what can go wrong here."
That last stage is the goal of this article. Go's approach to errors is verbose, yes. But it's verbose in the way a seatbelt is annoying: you only resent it until the day it matters. We'll look at what errors really are in Go, how to create and wrap them, how to inspect them, and how to design error handling that makes your API honest and your logs useful.
Errors are just values
In many languages, errors fly through the air as exceptions. A function throws one, and it sails up the call stack like a paper plane until someone, somewhere, catches it. Or nobody does, and your program dies dramatically.
Go doesn't do that. In Go, an error is a value, returned like any other. The built-in error type is tiny:
type error interface {
Error() string
}
Anything with an Error() string method is an error. That's the entire contract.
So a function that can fail says so in its signature:
func ParseAge(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
if n < 0 {
return 0, errors.New("age cannot be negative")
}
return n, nil
}
You can see, just from the first line, that this function may fail. There are no hidden exits. No surprise trapdoors. The caller must decide what to do, right there, in plain sight. That's the whole philosophy: failure is a normal part of the program, so treat it like normal code.
if err != nil is not a code smell
Let's address the elephant. Yes, you'll write this a lot:
user, err := repo.FindByID(ctx, id)
if err != nil {
return nil, err
}
People joke about it, but notice what it gives you: at every step, you've made an explicit decision about what happens on failure. In a language with exceptions, the question "what if this call fails?" can be answered by "somewhere above me, I hope." Here, you answer it on the spot.
That said, bare return err is often a missed opportunity, as we'll see in a moment.
Creating errors
There are three everyday ways to make an error.
1. errors.New, for simple fixed messages:
err := errors.New("insufficient stock")
2. fmt.Errorf, for messages with details:
err := fmt.Errorf("product %d has only %d units left", id, qty)
3. Custom types, when callers need structured information:
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("%s: %s", e.Field, e.Message)
}
Start with the first two. Reach for the third when a caller needs to do something with the details, such as showing "email: must contain @" next to the right form field.
Wrapping: leaving a trail of breadcrumbs
Suppose your database connection drops. The raw error might say:
connection refused
Helpful? About as helpful as a doctor saying "something's wrong." Where? Doing what? For whom?
This is where wrapping comes in. Use %w in fmt.Errorf to add context while keeping the original error inside:
func (s *OrderService) Get(ctx context.Context, id uint) (*domain.Order, error) {
order, err := s.orders.FindByID(ctx, id)
if err != nil {
return nil, fmt.Errorf("getting order %d: %w", id, err)
}
return order, nil
}
Each layer adds a sentence. By the time the error reaches your logs, it reads like a story:
handling GET /orders/42: getting order 42: finding order 42: connection refused
Now you know exactly where to look. Compare that to a bare connection refused buried in 10,000 log lines. Wrapping is the difference between a trail of breadcrumbs and a single mysterious crumb on the kitchen floor.
A style note: write wrap messages as short descriptions of what you were trying to do, in lowercase, without "failed to" or "error:" prefixes. The word "error" is already implied, and a chain like failed to get order: failed to find order: failed to query is like a person apologizing three times in a row.
Inspecting errors: errors.Is and errors.As
Wrapping creates a chain. How do you ask questions about it?
errors.Is: "is this error, or something inside it, this specific value?"
var ErrNotFound = errors.New("not found")
// ... deep in the repository
return fmt.Errorf("finding user %d: %w", id, ErrNotFound)
// ... up in the handler
if errors.Is(err, ErrNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
Even though the error has been wrapped several times, errors.Is walks the chain and finds the match. Never compare errors with == once wrapping is involved. The wrapper is a different value, so == will say no.
errors.As: "is there an error of this type in the chain? If so, give it to me."
var verr *ValidationError
if errors.As(err, &verr) {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"field": verr.Field,
"error": verr.Message,
})
return
}
Use Is for sentinel values ("is it the not-found error?") and As for typed errors ("is it a validation error, and what field?"). A common mnemonic: Is asks about identity, As asks about type and wants to unpack it.
Sentinel errors, typed errors, or just strings?
How much machinery do you need? A practical guide:
- If nobody needs to react to the specific failure, a plain
fmt.Errorfwith context is enough. Most errors fall here, and that's fine. - If callers need to branch on a particular condition ("not found," "already exists," "forbidden"), define a sentinel error and compare with
errors.Is. - If callers need data out of the error (which field, which limit), use a custom type with
errors.As.
Don't invent a hierarchy of fifty error types on day one. Add structure when a caller genuinely needs it. An error taxonomy no one uses is like a filing system for a library with three books.
Where errors should be handled (once)
Here's a rule that fixes an enormous number of messy codebases: handle each error exactly once. Either return it, or deal with it, but not both.
A classic mistake:
if err != nil {
log.Printf("failed: %v", err) // logs it...
return err // ...and passes it up to be logged again
}
Now the same failure shows up three times in your logs, once per layer, and during an incident you wonder whether you're seeing three separate problems. The fix: lower layers wrap and return. The place where the error finally stops, usually the handler or a middleware, logs it once and responds to the client.
Think of it as a relay race. Everyone carries the baton forward and adds notes. Only the person at the finish line announces the result.
Mapping errors to HTTP in one place
If every handler has its own giant switch on error types, you'll copy-paste them wrong. Centralize the translation:
// internal/handler/errors.go
func respondError(c *gin.Context, err error) {
var verr *domain.ValidationError
switch {
case errors.As(err, &verr):
c.JSON(http.StatusUnprocessableEntity, gin.H{
"error": verr.Message, "field": verr.Field,
})
case errors.Is(err, domain.ErrNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
case errors.Is(err, domain.ErrForbidden):
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
case errors.Is(err, domain.ErrConflict):
c.JSON(http.StatusConflict, gin.H{"error": "already exists"})
default:
log.Printf("internal error on %s %s: %v",
c.Request.Method, c.Request.URL.Path, err)
c.JSON(http.StatusInternalServerError,
gin.H{"error": "something went wrong"})
}
}
Then every handler ends its failure path with a single line: respondError(c, err).
Two important things happen here.
The default case is deliberately vague to the client. Never send raw internal errors to users. A message like pq: password authentication failed for user "app" is a gift to attackers and an embarrassment to you. The client gets "something went wrong"; the log gets the full wrapped chain.
Known business errors get honest, specific responses. "Not found" and "forbidden" are safe to say out loud. Be clear and consistent, and your frontend developer, possibly also you, will thank you.
Panics: the emergency exit
Go also has panic, which looks like exceptions but isn't meant to be used like them. A panic means "something is so wrong that the program can't continue sensibly": an impossible state, a programmer mistake, a nil map write.
Rules of thumb:
-
Don't use panic for ordinary failures. A missing record, bad input, or a network blip is an
error. - Do panic during startup if the app can't possibly run, like a missing required config value. Failing loudly at boot beats failing mysteriously at 3 a.m.
-
Put
gin.Recovery()in your middleware so that an accidental panic in one request returns a 500 instead of taking down the server.
Libraries almost never panic across their public boundary, and yours shouldn't either.
Errors in goroutines and loops
One last place errors get lost: concurrent code. If you launch a goroutine and it fails, nobody is waiting to receive its return value.
The errgroup package handles this elegantly:
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return s.sendEmail(ctx, order) })
g.Go(func() error { return s.updateInventory(ctx, order) })
if err := g.Wait(); err != nil {
return fmt.Errorf("post-order tasks: %w", err)
}
Wait blocks until all tasks finish and returns the first error. If one fails, the shared context is cancelled so the others can stop early. It's a tidy way to say "do these things in parallel, and tell me if anything broke."
And a small trap in loops: when you collect multiple errors, use errors.Join (Go 1.20+) to combine them instead of keeping only the first and discarding the rest.
Common mistakes
Ignoring errors with _. hash, _ := bcrypt.GenerateFromPassword(...) compiles beautifully and fails silently. If you truly intend to ignore an error, write a comment explaining why. If you can't explain why, don't ignore it.
Returning nil, nil. A function that returns no value and no error leaves the caller holding a nil pointer and no warning. Return a real error for "not found."
Comparing with == after wrapping. Use errors.Is.
Leaking internals to clients. Log the details, send the polite summary.
Logging and returning. Pick one. Handle once.
Wrapping with %v instead of %w. %v flattens the error into text and breaks the chain, so errors.Is stops working. When you want to keep the original inspectable, use %w.
Making errors too generic. errors.New("something went wrong") deep in your code tells your future self nothing. Name the operation.
Quick recap
- Errors in Go are ordinary values, returned and checked explicitly.
-
if err != nilisn't clutter. It's a decision point where you say what failure means. - Wrap with
%wto build a breadcrumb trail, and describe what you were doing. - Use
errors.Isfor specific values,errors.Asfor typed errors. - Define sentinel or typed errors only where callers need to react.
- Handle each error once: wrap and return in lower layers, log and respond at the edge.
- Centralize error-to-HTTP translation, and never leak internals to clients.
- Reserve
panicfor the truly impossible, and keepRecoverymiddleware on.
Top comments (0)