Creating standard error values

suggest change

There are several ways to create an error value.

errors.New

The simplest way is errors.New(msg string), which creates an error from a string.

return errors.New("error created with errors.New")

fmt.Errorf

For more complex error messages, fmt.Errorf(format string, args ...interface{}) takes a formatting string and arguments:

return fmt.Errorf("error created with %s", "fmt.Errorf")

For a format without %w, the text matches errors.New(fmt.Sprintf(...)), but the dynamic type is different, so the two errors do not compare equal with ==. A %w verb wraps another error so callers can use errors.Is and errors.As.

global error variable

// ErrGlobal exported so that others can compare returned error value with this variable
var ErrGlobal = errors.New("global error variable")

return ErrGlobal

Sometimes the error needs an identity so callers can test for this specific error. Declare a package-level variable, as ErrGlobal does above, and return that same value.

One example of such error from standard library is io.EOF although usually the naming convention for such errors is Err*.

You can also create custom error types.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents