github.com/google/martian/v3@v3.3.3/multierror.go (about) 1 // Copyright 2015 Google Inc. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package martian 16 17 import ( 18 "strings" 19 "sync" 20 ) 21 22 // MultiError is a collection of errors that implements the error interface. 23 type MultiError struct { 24 mu sync.RWMutex 25 errs []error 26 } 27 28 // NewMultiError returns a new MultiError. 29 func NewMultiError() *MultiError { 30 return &MultiError{} 31 } 32 33 // Error returns the list of errors separated by newlines. 34 func (merr *MultiError) Error() string { 35 merr.mu.RLock() 36 defer merr.mu.RUnlock() 37 38 var errs []string 39 for _, err := range merr.errs { 40 errs = append(errs, err.Error()) 41 } 42 43 return strings.Join(errs, "\n") 44 } 45 46 // Errors returns the error slice containing the error collection. 47 func (merr *MultiError) Errors() []error { 48 merr.mu.RLock() 49 defer merr.mu.RUnlock() 50 51 return merr.errs 52 } 53 54 // Add appends an error to the error collection. 55 func (merr *MultiError) Add(err error) { 56 merr.mu.Lock() 57 defer merr.mu.Unlock() 58 59 // Unwrap *MultiError to ensure that depth never exceeds 1. 60 if merr2, ok := err.(*MultiError); ok { 61 merr.errs = append(merr.errs, merr2.Errors()...) 62 return 63 } 64 65 merr.errs = append(merr.errs, err) 66 } 67 68 // Empty returns whether the *MultiError contains any errors. 69 func (merr *MultiError) Empty() bool { 70 return len(merr.errs) == 0 71 }