When wrapping errors in golang, should the %w verb be used at the beginning or at the end when creating the new error? Or it doesn’t matter because there’s no convention or recommendation – we can use whatever makes the error string easier to understand?
Eaxample when %w is used at the end:
if err != nil {
return fmt.Errorf("decompress %v: %w", name, err)
}
And an example when %w is used at the beginning:
if record.BoatSize != 0 {
err = fmt.Errorf("%w: boatSize is set", ErrInvalidBoatRecord)
}
>Solution :
The position of %w is not used when wrapping neither when unwrapping the error, so it does not matter.
Use whichever makes your error message clearer.
Usually adding it to the end is more common, it reads well when chaining the errors, going from general to more specific errors. For example:
IO error: file open error: permission error: user does not exist