Error messages in Go

When Go code propagates an error, the following pattern is very popular:

fmt.Errorf("failed to find a parking slot: %w", err)
// Or
fmt.Errorf("could not call mom: %w", err)

These “could not”, “failed to”, “unable to” make sense when my mind is in the local context of the function, method or package. But, in most of the cases I have to deal with, it makes the resulting log message overloaded with informational garbage:

unable to ask about the cat: failed to call mom: failed to do request: Get https://: context canceled

While discussing this issue with a colleague, we came up with the following “better” strategy:

  1. only the logger should express its attitude to the facts, using words “error”, “failed”, etc
  2. the business code must operate only with facts, e.g. “call mom”.
err := CallMom(number)
if err != nil {
    return fmt.Errorf("call mom (tel %s): %w", number, err)
}

This renders as following to the application logs:

error: ask about cat: call mom (tel 123): make request: Get https://: context canceled

For a long stack of errors, this makes the full error message more dense, showing more useful information per line.

All topics

applearduinoarm64askmeawsberlinbookmarksbuildkitcgocoffeecontinuous profilingCOVID-19designdockerdynamodbe-paperenglishenumesp8266firefoxgithub actionsGogooglegraphqlhomelabIPv6k3skuberneteslinuxmacosmaterial designmDNSmusicndppdneondatabaseobjective-cpasskeyspostgresqlpprofprofeferandomraspberry pirusttravis civs codewaveshareµ-benchmarks