How do you wrap errors in Go using fmt.Errorf with the %w verb, and why is error wrapping useful?
Last updated
Wrap with
fmt.Errorf("loading config: %w", err)to add context while keeping the original retrievable viaerrors.Is,errors.As, orerrors.Unwrap. Use%vto 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.