The Errors Package
For simple cases where you don’t need a custom struct, the standard library provides the errors package to create errors on the fly.
errors.New()
The errors.New() function takes a string and returns a simple error value.
import "errors"
func divide(x, y float64) (float64, error) {
if y == 0 {
return 0, errors.New("cannot divide by zero")
}
return x / y, nil
}
fmt.Errorf()
If you need to include dynamic data in your error message, fmt.Errorf is the preferred way. It works like Printf but returns an error.
err := fmt.Errorf("user %d not found", userID)
In modern Go (1.13+), you can also use %w to “wrap” an existing error with more context:
return fmt.Errorf("database failure: %w", originalErr)