Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
features: automatically wrap all feature probe errors
Instead of relying on repeated calls to fmt.Errorf("...: %w", err) to ensure we never return naked sentinels, add error wrappers at a few key locations. This abstracts and centralizes the wrapping logic to make the probe logic itself a bit leaner. Signed-off-by: Timo Beckers <timo@isovalent.com>
- Loading branch information
Showing
4 changed files
with
69 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package features | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
|
||
"github.com/cilium/ebpf" | ||
) | ||
|
||
// wrapProbeErrors wraps err to prevent callers from directly comparing | ||
// it to exported sentinels. Error rewriting in Go can be implemented by | ||
// deferring a closure over a named error return variable. This gives the | ||
// closure access to the stack space where the return value will be written, | ||
// allowing it to intercept and rewrite all returns, regardless of whether | ||
// or not the return statements use the named return variable. | ||
// | ||
// func foo() (err error) { | ||
// defer func() { | ||
// err = wrapProbeErrors(err) | ||
// } | ||
// return errors.New("this error will be wrapped") | ||
// } | ||
func wrapProbeErrors(err error) error { | ||
if err == nil { | ||
return nil | ||
} | ||
|
||
// Wrap all errors to prevent them from being compared directly | ||
// to exported sentinels by the caller. | ||
errStr := "%w" | ||
|
||
if !errors.Is(err, ebpf.ErrNotSupported) { | ||
// Wrap unexpected errors with an appropriate error string. | ||
errStr = "unexpected error during feature probe: %w" | ||
} | ||
|
||
return fmt.Errorf(errStr, err) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters