Errors, Wrapping & panic
Sentinel errors, custom error types, %w wrapping with errors.Is and errors.As, and recover.
Errors in Go are ordinary values that implement error (an Error() string method). Functions return them, callers check them, and wrapping adds context while keeping the original error inspectable.
Handling different errors
ErrMissing is a sentinel error, recognised with errors.Is.
RangeError is a custom type carrying the bad value, extracted with errors.As.
fmt.Errorf("...: %w", err) wraps an error with context; the chain can still be inspected.
A deferred function calling recover turns a panic (here an out-of-range index) into an error.
Errors vs panics
if err.Error() == "missing field" {... } if errors.Is(err, ErrMissing) {... }
Comparing error strings breaks as soon as the message is wrapped or reworded; errors.Is follows the wrap chain.
What is the difference between %w and %v in fmt.Errorf?
%w wraps the error so errors.Is/As can find it in the chain; %v only includes its text.