An error value reports whether an operation encountered a problem. Go functions commonly return their useful results first and an error last; a function that has no other result can return only an error. This convention makes potentially failing operations visible in their signatures. section 2.6.2 section 7.1
Listing 2.25 Documentation for os.ReadFile
func ReadFile(name string) ([]byte, error)
ReadFile reads the named file and returns the contents.
os.ReadFile returns file contents alongside an error value. section 2.6.2
Check the error as soon as it is returned. A nil error indicates success; a non-nil error needs handling. Keeping the check near the operation makes the control flow explicit rather than moving it to a separate exception-handling block. section 2.6.3 section 7.1
Listing 2.26 Logging an error and exiting
if err != nil {
log.Println(err)
os.Exit(1)
}
For a small program, logging the error and exiting with status 1 can be enough. section 2.6.3
The error type is an interface with one method, Error() string. The method supplies a message, while a concrete error type can carry additional information or behavior. section 7.2
Listing 7.1 main.go: Defining functions with error return values
package main
type Store interface {
Put(key string, val string) error #1
Get(key string) (string, error) #2
Delete(key string) error
}
A key/value store can expose failures directly: Put and Delete return an error, while Get returns a value and an error. section 7.1
Handling depends on the operation: return the error to a caller, add context, log and exit, retry, or explicitly ignore it. Discarding an error without considering it is normally an antipattern. section 7.2 section 7.4
