liveBook · Manning

Error value

As explained in Go in Action, Second Edition

An error value is a Go value of the error type that reports whether an operation encountered a problem.

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

How Go in Action, Second Edition covers it

How deep it goes
Explains return conventions, nil checks, the error interface, and handling choices; defers detailed wrapping and panic recovery.
Examples
Illustrates errors with os.ReadFile, a key/value store interface, and logging followed by os.Exit.
What you can do after
Apply error checks to function calls and choose whether to return, log, retry, or explicitly ignore a failure.
How it connects
Connects error values to multiple return values, interfaces, logging, and panic.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.