github.com/binkynet/BinkyNet@v1.12.1-0.20240421190447-da4e34c20be0/apis/util/error.go (about)

     1  // Copyright 2020 Ewout Prangsma
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // Author Ewout Prangsma
    16  //
    17  
    18  package util
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"io"
    24  )
    25  
    26  // IsStreamClosed returns true when the error indicates
    27  // a normal closing of a GRPC stream.
    28  func IsStreamClosed(err error) bool {
    29  	return err == io.EOF
    30  }
    31  
    32  // ContextCanceledOrUnexpected is used in errgroup.Go functions
    33  // to ensure that an error is returned when a "Runner" function
    34  // ended unexpectedly.
    35  // Returns:
    36  // - if ctx.Err() != nil -> ctx.Err()
    37  // - if err != nil -> wrap(err, "component returned an unexpected error")
    38  // - otherwise -> "component ended unexpectedly"
    39  func ContextCanceledOrUnexpected(ctx context.Context, err error, component string) error {
    40  	if err := ctx.Err(); err != nil {
    41  		return err
    42  	}
    43  	if err != nil {
    44  		return fmt.Errorf("%s returned an unexpected error: %w", component, err)
    45  	}
    46  	return fmt.Errorf("%s ended unexpectedly", component)
    47  }