diff --git a/exception.go b/exception.go index 09734c9..cad8845 100644 --- a/exception.go +++ b/exception.go @@ -4,11 +4,13 @@ import ( "bytes" "fmt" "os" + "reflect" "strings" ) type Custom interface { error + At(source any) Custom With(innerErr ...error) Custom IsSameAs(err error) bool } @@ -30,6 +32,13 @@ func (ex *custom) With(innerErr ...error) Custom { return ex } +func (ex *custom) At(source any) Custom { + if source != nil { + ex.message = fmt.Sprintf("%s in %s", ex.message, getType(source)) + } + return ex +} + func (ex *custom) IsSameAs(err error) bool { if err == nil { return false @@ -54,3 +63,14 @@ func getOsNewLine() string { } return "\r\n" } + +func getType[T any](source T) string { + typeName := "" + typeOf := reflect.TypeOf(source) + if typeOf != nil { + typeName = typeOf.String() + } else { + typeName = reflect.TypeOf((*T)(nil)).Elem().String() + } + return typeName +} diff --git a/exception_test.go b/exception_test.go index fb7d94c..52edadf 100644 --- a/exception_test.go +++ b/exception_test.go @@ -32,9 +32,9 @@ func (suite *CustomExceptionTestSuite) TestShouldAddInnerErrors() { func (suite *CustomExceptionTestSuite) TestShouldAddInnerErrorsAfterCreation() { ex := exception.NewCustom("fail") - ex.With(fmt.Errorf("innerError1"), fmt.Errorf("innerError2")) + ex.At(suite).With(fmt.Errorf("innerError1"), fmt.Errorf("innerError2")) suite.NotNil(ex) - suite.Equal(ex.Error(), "[fail]:\ninnerError1\ninnerError2") + suite.Equal(ex.Error(), "[fail in *exception_test.CustomExceptionTestSuite]:\ninnerError1\ninnerError2") } func (suite *CustomExceptionTestSuite) TestShouldCompareExceptions() {