github.com/searKing/golang/go@v1.2.117/errors/multi_go1.19.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build !go1.20 6 7 package errors 8 9 import ( 10 "errors" 11 "strings" 12 ) 13 14 var _ error = (*multiError)(nil) // verify that Error implements error 15 16 // Multi returns an error that wraps the given errors. 17 // Any nil error values are discarded. 18 // Join returns nil if every value in errs is nil. 19 // The error formats as the concatenation of the strings obtained 20 // by calling the Error method of each element of errs, with a '|' 21 // between each string. 22 // Deprecated: Use errors.Join instead since go1.20. 23 func Multi(errs ...error) error { 24 n := 0 25 for _, err := range errs { 26 if err != nil { 27 n++ 28 } 29 } 30 if n == 0 { 31 return nil 32 } 33 me := make(multiError, 0, n) 34 for _, err := range errs { 35 if err != nil { 36 me = append(me, err) 37 } 38 } 39 return me 40 } 41 42 type multiError []error 43 44 func (e multiError) Error() string { 45 var b strings.Builder 46 for i, err := range e { 47 if i > 0 { 48 b.WriteString("\n") 49 } 50 b.WriteString(err.Error()) 51 } 52 return b.String() 53 } 54 55 // Unwrap returns the error in e, if there is exactly one. If there is more than one 56 // error, Unwrap returns first non-nil error , since there is no way to determine which should be 57 // returned. 58 // Deprecated: Unwrap() []error supported instead since go1.20. 59 func (e multiError) Unwrap() error { 60 for _, err := range e { 61 if err != nil { 62 return err 63 } 64 } 65 // Return nil when e is nil, or has more than one error. 66 // When there are multiple errors, it doesn't make sense to return any of them. 67 return nil 68 } 69 70 // Is reports whether any error in multiError matches target. 71 // Deprecated: Unwrap() []error supported instead since go1.20. 72 func (e multiError) Is(target error) bool { 73 if target == nil { 74 for _, err := range e { 75 if err != nil { 76 return true 77 } 78 } 79 return false 80 } 81 for _, err := range e { 82 if err == nil { 83 continue 84 } 85 if errors.Is(err, target) { 86 return true 87 } 88 } 89 return false 90 } 91 92 // As finds the first error in err's chain that matches target, and if one is found, sets 93 // target to that error value and returns true. Otherwise, it returns false. 94 // Deprecated: Unwrap() []error supported instead since go1.20. 95 func (e multiError) As(target any) bool { 96 for _, err := range e { 97 if errors.As(err, target) { 98 return true 99 } 100 } 101 return false 102 }