github.com/searKing/golang/go@v1.2.117/error/multi/multi.go (about)

     1  // Copyright 2020 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  package multi
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  )
    11  
    12  // New returns an error with the supplied errors.
    13  // If no error contained, return nil.
    14  // Deprecated: Use errors.Multi instead.
    15  func New(errs ...error) error {
    16  	var has bool
    17  	for _, err := range errs {
    18  		if err != nil {
    19  			has = true
    20  			break
    21  		}
    22  	}
    23  	if !has {
    24  		return nil
    25  	}
    26  	return &multiError{
    27  		errs: errs,
    28  	}
    29  }
    30  
    31  type multiError struct {
    32  	errs []error
    33  }
    34  
    35  func (w *multiError) Error() string {
    36  	if w == nil || len(w.errs) == 0 {
    37  		return ""
    38  	}
    39  	message := w.errs[0].Error()
    40  	for _, err := range w.errs[1:] {
    41  		message += "|" + err.Error()
    42  	}
    43  
    44  	return message
    45  }
    46  
    47  func (w *multiError) Format(s fmt.State, verb rune) {
    48  	if w == nil {
    49  		return
    50  	}
    51  	switch verb {
    52  	case 'v':
    53  		if s.Flag('+') {
    54  			if len(w.errs) == 0 {
    55  				return
    56  			}
    57  
    58  			_, _ = io.WriteString(s, "Multiple errors occurred:\n\t")
    59  
    60  			_, _ = io.WriteString(s, w.errs[0].Error())
    61  
    62  			for _, err := range w.errs[1:] {
    63  				_, _ = fmt.Fprintf(s, "|%+v", err)
    64  			}
    65  			return
    66  		}
    67  		fallthrough
    68  	case 's', 'q':
    69  		_, _ = io.WriteString(s, w.Error())
    70  	}
    71  }