Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convention for wrapping errors in Golang

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading