git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/validate/error.go (about)

     1  package validate
     2  
     3  import (
     4  	"sort"
     5  	"strings"
     6  )
     7  
     8  // Errors is an array of multiple errors and conforms to the error interface.
     9  type Errors []error
    10  
    11  // Errors returns itself.
    12  func (es Errors) Errors() []error {
    13  	return es
    14  }
    15  
    16  func (es Errors) Error() string {
    17  	var errs []string
    18  	for _, e := range es {
    19  		errs = append(errs, e.Error())
    20  	}
    21  	sort.Strings(errs)
    22  	return strings.Join(errs, ";")
    23  }
    24  
    25  // Error encapsulates a name, an error and whether there's a custom error message or not.
    26  type Error struct {
    27  	Name                     string
    28  	Err                      error
    29  	CustomErrorMessageExists bool
    30  
    31  	// Validator indicates the name of the validator that failed
    32  	Validator string
    33  	Path      []string
    34  }
    35  
    36  func (e Error) Error() string {
    37  	if e.CustomErrorMessageExists {
    38  		return e.Err.Error()
    39  	}
    40  
    41  	errName := e.Name
    42  	if len(e.Path) > 0 {
    43  		errName = strings.Join(append(e.Path, e.Name), ".")
    44  	}
    45  
    46  	return errName + ": " + e.Err.Error()
    47  }