Sobes.tech
Senior

What is the difference between %v and %w in formatting? And how to correctly add error handling in the Do interface?

sobes.tech AI

Answer from AI

In Go, when formatting errors using the fmt package:

  • %v — outputs the error as is, just the error message.
  • %w — used for wrapping an error to preserve the error chain (wrapping), allowing the use of errors.Is and errors.As for checking.

Example:

if err != nil {
    return fmt.Errorf("error reading file: %w", err) // wrapping the error
}

Here, %w allows embedding the original error inside a new one, preserving the information.

Regarding the Do interface, if it returns an error, it is better to handle errors through the return value rather than panic or log inside the method.

For example:

type Doer interface {
    Do() error
}

func Process(d Doer) error {
    if err := d.Do(); err != nil {
        return fmt.Errorf("error executing Do: %w", err)
    }
    return nil
}

This way, the caller can handle the error as they see fit, rather than losing or ignoring it.

What is the difference between %v and %w in… - sobes.tech