errors.As finds an error in an error chain that is assignable to a specified concrete type or interface, then stores the matching value in a destination. It exposes task-specific data that the error interface alone does not provide. section 7.10
Use errors.As when handling an error requires its underlying type or data:
- Declare a variable of the desired error type, commonly a pointer type. section 7.10
- Pass a pointer to that variable, allowing errors.As to inspect the chain and populate it. section 7.10
- Check the returned boolean before reading the populated value. section 7.10
- Handle the recovered details at the layer that can act on them, while allowing errors to flow through intervening layers. section 7.10
Recovering failed bulk keys
A BulkGet operation can return a bulkGetError containing keys that were not found. The caller uses errors.As to recover that value, then inserts temporary placeholders for each key. Because bulkGetError is commonly handled through a pointer-shaped destination, the destination may require a pointer to a pointer. section 7.10
Listing 7.18 main.go: Getting the underlying bulk error keys
func main() {
...
if _, err := store.BulkGet("foo"); err != nil {
log.Println(err)
} else {
log.Println("no error on bulk get")
}
if _, err := store.BulkGet("foo", "fizz"); err != nil {
log.Println(err)
}
if _, err := store.BulkGet("foo", "fizz"); err != nil {
var berr bulkGetError #1
if errors.As(err, &berr) { #2
for _, key := range berr { #3
_ = store.Put(key, "temp") #4
}
}
}
if _, err := store.BulkGet("foo"); err != nil {
log.Println(err)
} else {
log.Println("no error on bulk get")
}
}
The listing shows errors.As recovering bulkGetError, iterating over its keys, and inserting temporary values into the store. section 7.10



