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




