Middle+
How to work with errors in Go, how to wrap an error?
sobes.tech AI
Answer from AI
In Go, errors are represented by the error type, which is an interface with the method Error() string. It is common to return errors from functions and check them immediately after the call.
To wrap an error and add context, you can use the fmt package with the fmt.Errorf function and %w for wrapping, or use third-party libraries such as pkg/errors.
Example of wrapping an error with fmt.Errorf:
if err := someFunc(); err != nil {
return fmt.Errorf("someFunc failed: %w", err)
}
This allows you to preserve the original error and add additional description. Later, you can check for a specific error using errors.Is or extract it with errors.Unwrap.
This approach improves error tracing and simplifies problem diagnosis.