github.com/whoyao/protocol@v0.0.0-20230519045905-2d8ace718ca5/utils/err_array.go (about)

     1  package utils
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  
     7  	"github.com/livekit/psrpc"
     8  )
     9  
    10  type ErrArray struct {
    11  	errs []error
    12  }
    13  
    14  func (e *ErrArray) AppendErr(err error) {
    15  	e.errs = append(e.errs, err)
    16  }
    17  
    18  func (e *ErrArray) ToError() psrpc.Error {
    19  	if len(e.errs) == 0 {
    20  		return nil
    21  	}
    22  
    23  	code := psrpc.Unknown
    24  	var errStr []string
    25  
    26  	// Return the code for the first error of type psrpc.Error
    27  	for _, err := range e.errs {
    28  		var psrpcErr psrpc.Error
    29  
    30  		if code == psrpc.Unknown && errors.As(err, &psrpcErr) {
    31  			code = psrpcErr.Code()
    32  		}
    33  
    34  		errStr = append(errStr, err.Error())
    35  	}
    36  
    37  	return psrpc.NewErrorf(code, "%s", strings.Join(errStr, "\n"))
    38  }