gopkg.in/essentialkaos/ek.v3@v3.5.1/errutil/errutil.go (about)

     1  // Package errutil provides methods for working with errors
     2  package errutil
     3  
     4  // ////////////////////////////////////////////////////////////////////////////////// //
     5  //                                                                                    //
     6  //                     Copyright (c) 2009-2016 Essential Kaos                         //
     7  //      Essential Kaos Open Source License <http://essentialkaos.com/ekol?en>         //
     8  //                                                                                    //
     9  // ////////////////////////////////////////////////////////////////////////////////// //
    10  
    11  // Errors is struct for handling many errors at once
    12  type Errors struct {
    13  	num    int
    14  	errors []error
    15  }
    16  
    17  // ////////////////////////////////////////////////////////////////////////////////// //
    18  
    19  // NewErrors creates new struct
    20  func NewErrors() *Errors {
    21  	return &Errors{}
    22  }
    23  
    24  // Chain execute functions in chain and if one of them return error
    25  // this function stop chain execution and return given error
    26  func Chain(funcs ...func() error) error {
    27  	var err error
    28  
    29  	for _, fc := range funcs {
    30  		err = fc()
    31  
    32  		if err != nil {
    33  			return err
    34  		}
    35  	}
    36  
    37  	return err
    38  }
    39  
    40  // ////////////////////////////////////////////////////////////////////////////////// //
    41  
    42  // Add adds new error to slice
    43  func (e *Errors) Add(errs ...error) *Errors {
    44  	if errs == nil {
    45  		return e
    46  	}
    47  
    48  	for _, err := range errs {
    49  		if err != nil {
    50  			e.errors = append(e.errors, err)
    51  			e.num++
    52  		}
    53  	}
    54  
    55  	return e
    56  }
    57  
    58  // Last return last error in slice
    59  func (e *Errors) Last() error {
    60  	if e.errors == nil || e.num == 0 {
    61  		return nil
    62  	}
    63  
    64  	return e.errors[e.num-1]
    65  }
    66  
    67  // All return all errors in slice
    68  func (e *Errors) All() []error {
    69  	if e.errors == nil {
    70  		return make([]error, 0)
    71  	}
    72  
    73  	return e.errors
    74  }
    75  
    76  // HasErrors check if slice contains errors
    77  func (e *Errors) HasErrors() bool {
    78  	if e.errors == nil {
    79  		return false
    80  	}
    81  
    82  	return e.num != 0
    83  }
    84  
    85  // Num return number of errors
    86  func (e *Errors) Num() int {
    87  	return e.num
    88  }