Rrors.new Vs Fmt.errorf
Fast recall
Quick revision
Core answer
Practical understanding of Errors New.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
They overlap but serve different jobs. errors.New is the fixed case: one string, one error, no formatting. fmt.Errorf is the richer case: it builds the message from a format string and arguments, so the error can carry the specifics — the file name that failed, the URL that timed out, the index that was out of range.
errors.New("could not open file") // fixed
fmt.Errorf("could not open %s: %w", path, err) // context + causeThe second example shows the bigger difference: %w. When fmt.Errorf's format contains %w, the returned error records the wrapped error as unwrap-able — errors.Is and errors.As can walk through the new message into the original cause. %v would embed the cause's text but sever the chain. So the choice is really: no message assembly (errors.New), assembly without a cause (Errorf with %v), or assembly that preserves the cause for inspection (Errorf with %w).
Rule of thumb: errors.New for fixed identities and sentinels; Errorf whenever runtime values belong in the message; %w whenever the caller below you may need to match or extract the underlying error.
Rrors.new Vs Fmt.errorf
Direct Answer
errors.New: fixed string. fmt.Errorf: formatted message; with %w it also wraps a cause for errors.Is/As. Use Errorf when you need context or values in the message.
Deep Dive & Architecture
The %w vs %v difference is the interview-worthy part, because they print identically and differ only in what they preserve:
base := errors.New("disk full")
withW := fmt.Errorf("write config: %w", base)
withV := fmt.Errorf("write config: %v", base)
errors.Is(withW, base) // true — chain intact
errors.Is(withV, base) // false — text only, no link
Both print as 'write config: disk full'. Only the %w version answers 'was the underlying cause disk full?' — because %w tells fmt.Errorf to store the cause in the error's Unwrap chain, and errors.Is walks that chain. With %v the cause's text is baked into the string at construction and the value itself is discarded.
That's why style guides settled on: wrap with %w when the caller might need the cause (most layers), use %v when the cause is genuinely only for humans (top-level log formatting), and reach for errors.New only when there's nothing to say beyond the identity.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Errors New, and when would you use it?
- How would you compare Errors New with an alternative?
- What is a common mistake when using Errors New?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.