add IsSameAs method

This commit is contained in:
admin 2025-08-07 15:50:06 +02:00
parent 1f211de8ef
commit e9716a72e6
2 changed files with 17 additions and 0 deletions

View File

@ -4,11 +4,13 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"os" "os"
"strings"
) )
type Custom interface { type Custom interface {
error error
With(innerErr ...error) Custom With(innerErr ...error) Custom
IsSameAs(err error) bool
} }
func NewCustom(message string, innerErr ...error) Custom { func NewCustom(message string, innerErr ...error) Custom {
@ -28,6 +30,10 @@ func (ex *custom) With(innerErr ...error) Custom {
return ex return ex
} }
func (ex *custom) IsSameAs(err error) bool {
return strings.HasPrefix(err.Error(), fmt.Sprintf("[%s]:", ex.message))
}
func (ex *custom) Error() string { func (ex *custom) Error() string {
buf := bytes.NewBufferString("") buf := bytes.NewBufferString("")
if len(ex.innerErrors) > 0 { if len(ex.innerErrors) > 0 {

View File

@ -37,6 +37,17 @@ func (suite *CustomExceptionTestSuite) TestShouldAddInnerErrorsAfterCreation() {
suite.Equal(ex.Error(), "[fail]:\ninnerError1\ninnerError2") suite.Equal(ex.Error(), "[fail]:\ninnerError1\ninnerError2")
} }
func (suite *CustomExceptionTestSuite) TestShouldCompareExceptions() {
InvalidArgumentException := exception.NewCustom("InvalidArgumentException")
NotFoundException := exception.NewCustom("NotFoundException")
customErr := fmt.Errorf("something")
suite.True(InvalidArgumentException.IsSameAs(InvalidArgumentException))
suite.False(NotFoundException.IsSameAs(InvalidArgumentException))
suite.False(NotFoundException.IsSameAs(customErr))
suite.False(InvalidArgumentException.IsSameAs(customErr))
}
func TestCustomExceptionTestSuite(t *testing.T) { func TestCustomExceptionTestSuite(t *testing.T) {
suite.Run(t, new(CustomExceptionTestSuite)) suite.Run(t, new(CustomExceptionTestSuite))
} }