Skip to content

fix: use %w in Prefix so errors.Is and errors.As work through prefixed errors#155

Open
amitmishra11 wants to merge 1 commit into
hashicorp:mainfrom
amitmishra11:fix/prefix-preserve-error-wrapping
Open

fix: use %w in Prefix so errors.Is and errors.As work through prefixed errors#155
amitmishra11 wants to merge 1 commit into
hashicorp:mainfrom
amitmishra11:fix/prefix-preserve-error-wrapping

Conversation

@amitmishra11

Copy link
Copy Markdown

Bug

Prefix wraps each constituent error (and non-multierror values) with
fmt.Errorf("%s %s", prefix, e). Using the %s verb formats the
original error into a plain string, discarding the error value. As a
result, errors.Is and errors.As cannot see through the prefixed
wrapper to reach the original error.

Reported in #56.

Reproduction:

sentinel := errors.New("sentinel")

// non-multierror path
result := multierror.Prefix(sentinel, "context:")
fmt.Println(errors.Is(result, sentinel)) // false -- wrong

// multierror path
multi := &multierror.Error{Errors: []error{sentinel}}
prefixed := multierror.Prefix(multi, "context:")
fmt.Println(errors.Is(prefixed, sentinel)) // false -- wrong

Fix

Replace %s with %w in both fmt.Errorf calls inside Prefix. The
%w verb wraps the original error so the standard library error chain
traversal can reach it. The formatted message is identical
("<prefix> <original message>"), so callers that only inspect the
string representation are unaffected.

Test

Added TestPrefix_ErrorsIs which asserts that errors.Is finds the
original sentinel through both the non-multierror and multierror paths of
Prefix.

All existing tests continue to pass.

…d errors

Prefix wraps each constituent error with fmt.Errorf using the %s verb,
which formats the original error into a plain string. This means the
original error value is lost, so errors.Is and errors.As cannot find it
when traversing the wrapped chain.

Switching to %w preserves the wrapping relationship. The formatted error
message is identical ("<prefix> <original message>"), so existing callers
that inspect only the string output are unaffected.

Fixes hashicorp#56
@amitmishra11 amitmishra11 requested a review from a team as a code owner July 3, 2026 14:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant