Error wrapping that stays inspectable with errors.Is and errors.As

6561
0

In production, you want errors that are both human-readable and machine-checkable. I wrap errors with %w so callers can still match them using errors.Is and errors.As. This avoids string comparisons like if err.Error() == ..., which break on refactors. I also like defining sentinel errors for well-known conditions (ErrNotFound, ErrConflict) and returning them from lower layers with context using fmt.Errorf. The service layer can then map those to HTTP status codes without losing the original cause. The important discipline is consistency: don’t mix ad-hoc errors with sentinel errors for the same condition. If you follow that rule, you get clean logs and predictable error handling across the codebase.