diff --git a/model/rulefmt/rulefmt.go b/model/rulefmt/rulefmt.go index c838e840e7..6af79f6ac4 100644 --- a/model/rulefmt/rulefmt.go +++ b/model/rulefmt/rulefmt.go @@ -53,6 +53,11 @@ func (err *Error) Error() string { return fmt.Sprintf("group %q, rule %d, %q: %v", err.Group, err.Rule, err.RuleName, err.Err.err) } +// Unwrap unpacks wrapped error for use in errors.Is & errors.As. +func (err *Error) Unwrap() error { + return &err.Err +} + // WrappedError wraps error with the yaml node which can be used to represent // the line and column numbers of the error. type WrappedError struct { @@ -75,6 +80,11 @@ func (we *WrappedError) Error() string { return we.err.Error() } +// Unwrap unpacks wrapped error for use in errors.Is & errors.As. +func (we *WrappedError) Unwrap() error { + return we.err +} + // RuleGroups is a set of rule groups that are typically exposed in a file. type RuleGroups struct { Groups []RuleGroup `yaml:"groups"` diff --git a/model/rulefmt/rulefmt_test.go b/model/rulefmt/rulefmt_test.go index 408638f48c..d79ee94e29 100644 --- a/model/rulefmt/rulefmt_test.go +++ b/model/rulefmt/rulefmt_test.go @@ -15,6 +15,7 @@ package rulefmt import ( "errors" + "io" "path/filepath" "testing" @@ -303,3 +304,27 @@ func TestWrappedError(t *testing.T) { }) } } + +func TestErrorUnwrap(t *testing.T) { + err1 := errors.New("test error") + + tests := []struct { + wrappedError *Error + unwrappedError error + }{ + { + wrappedError: &Error{Err: WrappedError{err: err1}}, + unwrappedError: err1, + }, + { + wrappedError: &Error{Err: WrappedError{err: io.ErrClosedPipe}}, + unwrappedError: io.ErrClosedPipe, + }, + } + + for _, tt := range tests { + t.Run(tt.wrappedError.Error(), func(t *testing.T) { + require.ErrorIs(t, tt.wrappedError, tt.unwrappedError) + }) + } +}