|
|
|
|
|
by GeneralMayhem
478 days ago
|
|
One thing that `if err != nil { return err }` lets you do, which panic/recover doesn't, is annotate errors with context. If you're throwing from 5 layers deep in the call stack, and two of those layers are loops that invoke the lower layers for each element of a list, you probably really want to know which element it was that failed. At that point, you have two options: 1. Pass a context trace into every function, so that it can panic with richer meaning. That's a right pain very quickly. 2. Return errors, propagating them up the stack with more context: for i, x := range listOfThings {
y, err := processThing(x)
if err != nil {
return fmt.Errorf("thing %d (%s) failed: %w", i, x, err)
}
}
|
|