Go Reference ยท Errors, I/O and Files
Go errors.New() function
Reference for Go errors.New: create a simple error from a string, define sentinel errors, why two errors with equal text differ, and when to use fmt.Errorf.
errors.New(text) returns a new value of type error whose message is the string you pass. It is the simplest way to create an error, and the usual way to define sentinel errors: package-level variables that callers compare against to find out what went wrong.
Each call returns a pointer to a fresh internal value, so two errors made from the same text are not equal. That is deliberate: identity, not wording, decides whether two errors are the same.
var ErrNotFound = errors.New("not found")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func New(text string) error
| Name | Description |
|---|---|
text |
The message returned by the error's Error() method. |
Returns: a non-nil error. The dynamic type is the unexported *errors.errorString, which is why %T prints *errors.errorString.
Edge cases: an empty string is legal and gives an error with an empty message. New never returns nil.
Usage notes
- Use it for fixed messages. If the message needs values (an ID, a file name), use
fmt.Errorf()instead; if callers need to inspect fields, define your own error type. - Declare sentinels once at package level and compare with
errors.Is(). Creatingerrors.Newinside a function and comparing it later never matches. - Naming convention:
ErrSomethingfor variables; messages start lowercase and have no trailing period or newline. - Do not repeat the package name in the message the way a long chain would; wrappers add context as the error travels up (
"open config: not found"). - Comparison works because the values are pointers. The same pointer is the same error, even if the text matches another error.
- Exporting a sentinel commits you to keeping it. Unexported errors can change freely.
- Cheap but not free: each call allocates, which is why sentinels are created once, not per failure.