liveBook · Manning

Error type

As explained in Go in Action, Second Edition

An error type is Go's interface type for representing failed or abnormal operation results through an Error method.

A function that can fail needs a predictable way to report failure without hiding it from its caller. In Go, it commonly returns an error as its final value: Put(key, value) returns error, while Get(key) returns (string, error). Check err != nil immediately after the call, then decide how to proceed. section 7.1

The error type is an interface with one method: Error() string. A non-nil error reports that something went wrong; Error supplies its message. Any type with that method can also carry information beyond the message. section 7.2

Handle the value where it becomes available:

  • Return it to the caller, adding meaningful context when needed. section 7.13
  • Inspect it and act, such as retrying a failed operation. Use errors.Is for a particular error and errors.As for a particular error type. section 7.2 section 7.13
  • Reserve panic for truly unexpected conditions rather than ordinary operation failures. section 7.13
Listing 7.15 main.go: Defining a new error type
type bulkGetError []string #1

func (e bulkGetError) addKey(key string) bulkGetError { #2
	return append(e, key)
}

func (e bulkGetError) Error() string { #3
	if len(e) == 0 {
		return ""
	}
	return fmt.Sprintf("missing keys: %s", strings.Join(e, ","))
}

A slice-backed error holds missing keys, provides a method to add one, and implements Error() to turn the collected keys into a message. section 7.9

Reporting a partial bulk lookup

A key/value store’s BulkGet can collect keys it cannot find while retrieving the others. If any are missing, it returns the retrieved values alongside the custom error; otherwise, it returns nil as the error. The caller can log the message or inspect the error type when it needs the missing-key data. section 7.9 section 7.13

How Go in Action, Second Edition covers it

How deep it goes
Defines the one-method interface and works through a slice-backed custom error, without descending below interface behavior.
Examples
Uses key/value store operations and a bulk lookup that collects missing keys in a custom error.
What it assumes
Assumes familiarity with Go functions, return values, and interfaces; defines the error interface itself.
What you can do after
Build it from scratch by implementing Error() string on a custom type and returning it when a bulk lookup finds missing keys.
How it connects
Connects interfaces and multiple return values to sentinel errors, error wrapping, errors.Is, and errors.As.

Also explained in

Compare how 5 books explain error type →

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.