github.com/cloudwego/kitex@v0.9.0/pkg/utils/err_chain.go (about)

     1  /*
     2   * Copyright 2021 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  // Package utils .
    18  package utils
    19  
    20  import "strings"
    21  
    22  // DefaultErrorSeparator is the separator for string representations of errors hold by ErrChain.
    23  const DefaultErrorSeparator = " | "
    24  
    25  // ErrChain is used to pack multiple errors.
    26  // The zero value of ErrChain is ready to use.
    27  type ErrChain struct {
    28  	errs []error
    29  	sep  *string
    30  }
    31  
    32  // UseSeparator sets the separator of the current ErrChain instance.
    33  func (e *ErrChain) UseSeparator(sep string) {
    34  	e.sep = &sep
    35  }
    36  
    37  // Append is not concurrency safe.
    38  func (e *ErrChain) Append(err error) {
    39  	e.errs = append(e.errs, err)
    40  }
    41  
    42  // HasError returns if there's error in the chain.
    43  func (e ErrChain) HasError() bool {
    44  	return len(e.errs) > 0
    45  }
    46  
    47  // Error implements the error interface.
    48  func (e ErrChain) Error() string {
    49  	if !e.HasError() {
    50  		return ""
    51  	}
    52  
    53  	sep := DefaultErrorSeparator
    54  	if e.sep != nil {
    55  		sep = *e.sep
    56  	}
    57  
    58  	var sb strings.Builder
    59  	sb.WriteString(e.errs[0].Error())
    60  	for i := 1; i < len(e.errs); i++ {
    61  		sb.WriteString(sep)
    62  		sb.WriteString(e.errs[i].Error())
    63  	}
    64  	return sb.String()
    65  }