How do you wrap errors in Go using fmt.Errorf with the %w verb, and why is error wrapping useful?

Last updated 20 June 2026

  • Wrap with fmt.Errorf("loading config: %w", err) to add context while keeping the original retrievable via errors.Is, errors.As, or errors.Unwrap. Use %v to deliberately flatten it.

  • Wrapping builds a layered message showing the path the error traveled, while callers can still inspect the root cause programmatically.

  • Caveat: a wrapped error becomes part of your API contract, so avoid wrapping implementation details you want to hide.

  • https://go.dev/blog/go1.13-errors
All Golang interview questions