]> 127.0.0.1 Git - part/.git/commitdiff
1 v0.28.20240114140844
authorqydysky <qydysky@foxmail.com>
Sun, 14 Jan 2024 14:03:07 +0000 (22:03 +0800)
committerqydysky <qydysky@foxmail.com>
Sun, 14 Jan 2024 14:03:07 +0000 (22:03 +0800)
errors/errors.go
errors/errors_test.go

index 86045dee46fa973d4ff0cc8f2d84b93d2fd0a60f..ba3aedf0a4be8a64b8140c9621b4b30324e86efe 100644 (file)
@@ -1,5 +1,10 @@
 package errors
 
+import (
+       "errors"
+       "fmt"
+)
+
 type Error struct {
        son    interface{}
        reason string
@@ -38,3 +43,70 @@ func New(reason string, action string) Error {
                action: action,
        }
 }
+
+func Join(e ...error) error {
+       if len(e) == 0 {
+               return nil
+       }
+
+       var errs []error
+       for _, v := range e {
+               if e, ok := v.(interface {
+                       Unwrap() []error
+               }); ok {
+                       errs = append(errs, e.Unwrap()...)
+               } else {
+                       errs = append(errs, v)
+               }
+       }
+
+       return errors.Join(errs...)
+}
+
+func Unwrap(e error) []error {
+       if e == nil {
+               return []error{}
+       }
+
+       if e, ok := e.(interface {
+               Unwrap() []error
+       }); ok {
+               return e.Unwrap()
+       }
+
+       return []error{errors.Unwrap(e)}
+}
+
+func ErrorFormat(e error, format ...func(error) string) (s string) {
+       if e == nil {
+               return ""
+       }
+
+       if se, ok := e.(interface {
+               Unwrap() []error
+       }); ok {
+               for _, v := range se.Unwrap() {
+                       if len(format) > 0 {
+                               s += format[0](v)
+                       } else {
+                               s += e.Error() + "\n"
+                       }
+               }
+       } else if len(format) > 0 {
+               s += format[0](e)
+       } else {
+               s += e.Error()
+       }
+
+       return
+}
+
+var (
+       ErrSimplifyFunc = func(e error) string {
+               if es := e.Error(); len(es) > 20 {
+                       return fmt.Sprintf("%.16s...\n", es)
+               } else {
+                       return es + "\n"
+               }
+       }
+)
index 885baa4c5ceded191c82726ac9d572804c5fb8c7..7453611760863429466e58e131383559f8c480f1 100644 (file)
@@ -1,6 +1,10 @@
 package errors
 
-import "testing"
+import (
+       "errors"
+       "io"
+       "testing"
+)
 
 func TestXxx(t *testing.T) {
        var err error
@@ -25,3 +29,14 @@ func TestXxx(t *testing.T) {
                t.Fail()
        }
 }
+
+func Test1(t *testing.T) {
+       e := Join(io.EOF, io.ErrClosedPipe)
+       e = Join(io.EOF, e)
+       if !errors.Is(e, io.ErrClosedPipe) {
+               t.FailNow()
+       }
+       if ErrorFormat(e, ErrSimplifyFunc) != "EOF\nEOF\nio: read/write o...\n" {
+               t.FailNow()
+       }
+}