exception/exception.go
2025-08-07 15:56:29 +02:00

57 lines
1017 B
Go

package exception
import (
"bytes"
"fmt"
"os"
"strings"
)
type Custom interface {
error
With(innerErr ...error) Custom
IsSameAs(err error) bool
}
func NewCustom(message string, innerErr ...error) Custom {
return &custom{
message: message,
innerErrors: innerErr,
}
}
type custom struct {
message string
innerErrors []error
}
func (ex *custom) With(innerErr ...error) Custom {
ex.innerErrors = append(ex.innerErrors, innerErr...)
return ex
}
func (ex *custom) IsSameAs(err error) bool {
if err == nil {
return false
}
return strings.HasPrefix(err.Error(), fmt.Sprintf("[%s]:", ex.message))
}
func (ex *custom) Error() string {
buf := bytes.NewBufferString("")
if len(ex.innerErrors) > 0 {
for _, innerE := range ex.innerErrors {
buf.WriteString(getOsNewLine())
buf.WriteString(innerE.Error())
}
}
return fmt.Sprintf("[%s]:%s", ex.message, buf.String())
}
func getOsNewLine() string {
if fmt.Sprintf("%v", os.PathSeparator) != "/" {
return "\n"
}
return "\r\n"
}