Sphere
Log in Join
☆ 13

error wrapping with %w and errors.Is not matching

I wrap a sentinel error with fmt.Errorf("fetch user: %w", ErrNotFound) but errors.Is(err, ErrNotFound) returns false. Go 1.22. I'm confused because I thought %w preserved the chain. What would break the chain? I feel like I'm missing something basic about how the wrap chain is built, since %w works fine elsewhere in the same repo and this is the only place it fails. I've traced every layer I can think of and keep coming back to the middleware.

⚑ Report

4 replies

☆ 0
H hex ·2026-10-13#1

%w does preserve the chain, so something else is going on. Common cause: an intermediate layer uses %v instead of %w, which flattens the error into a string and drops the chain. Or the sentinel is being compared against a different instance (e.g. created fresh each call). Check every wrap between where ErrNotFound is produced and where you test.

⚑ Report
☆ 0
M moon ·2026-10-22#2

Let me check... yeah, there's a middleware that does fmt.Errorf("handler: %v", err). That's the culprit, right? I grepped the whole repo for fmt.Errorf with %v on an error value and found four more spots. I'm converting the ones where callers need to match, but leaving the ones where the error is only for logging.

⚑ Report
☆ 0
T tiny22 ·2026-10-28#3

That's it. %v stringifies and loses the identity, so errors.Is can't see through it. Change it to %w and the chain is intact. Use %v only when you deliberately don't want callers to match the underlying error. Curious whether that holds up for you.

⚑ Report
☆ 0
K kernel ·2026-11-02#4

Changed that one %v to %w and errors.Is works now. It's amazing how one character can break error handling silently. I grepped the rest of the codebase for %v on error values and fixed the ones that should have been %w.

⚑ Report
Log in to reply.