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.

A Go function can return an error value alongside its result. By convention, the error comes last, making a potentially failing operation visible in the function signature. A nil error means the operation succeeded; a non-nil error needs a decision at the call site. section 2.6.2 section 7.1

Listing 7.3 The error interface
type error interface {
	Error() string
}

The error type is an interface with one method, Error() string. A non-nil value reports that something happened; its message reports what. An error can also carry more information or behavior. section 7.2

Reading a file

os.ReadFile(filename) returns file contents and an error. Capture both, then check err immediately. For a small program, a non-nil error can be logged to standard error before os.Exit(1); continue using the contents only when the check passes. section 2.6.2 section 2.6.3

The same design works in an application interface: a key/value store might declare Put and Delete as returning error, and Get as returning (string, error). Callers can see which operations may fail and handle each result near the call rather than in a distant exception handler. section 7.1

After a non-nil check, choose a response that fits the failure:

  • Return the error to the caller, with additional context if useful. section 7.2 section 7.4
  • Retry, or log and exit when the program cannot continue. section 7.2
  • Ignore it only deliberately; discarding an error is normally an antipattern. section 7.4

How Go in Action, Second Edition covers it

How deep it goes
Defines the error interface and works through return conventions, nil checks, and handling choices; defers more detailed error handling.
Examples
Uses os.ReadFile, a key/value store interface, and logging followed by process exit.
What it assumes
Builds on function return values and interfaces while defining the error type and nil-check pattern explicitly.
What you can do after
Practice/perform immediate nil checks, then propagate, annotate, retry, log, or deliberately ignore an error.
How it connects
Connects multiple return values, interfaces, nil checks, logging, error propagation, and exception handling.

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.