Creating standard error values

suggest change

There are several ways to create an error value.


The simplest way, errors.New(msg string) creates error value from string.

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


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")

It’s a shortcut for errors.New(fmt.Sprintf(...)).

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 you want the error to have an identity so that callers can test if returned error is this specific error. You can do it by declaring global variable as ErrGlobal in example above.

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:

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

Table Of Contents