github.com/grafana/pyroscope@v1.18.0/pkg/util/httpgrpcutil/errors.go (about)

     1  // SPDX-License-Identifier: AGPL-3.0-only
     2  
     3  package httpgrpcutil
     4  
     5  import (
     6  	"net/http"
     7  
     8  	"github.com/grafana/pyroscope/pkg/util/httpgrpc"
     9  )
    10  
    11  // PrioritizeRecoverableErr checks whether in the given slice of errors there is a recoverable error, if yes then it will
    12  // return the first recoverable error, if not then it will return the first non-recoverable error, if there is no
    13  // error at all then it will return nil.
    14  func PrioritizeRecoverableErr(errs ...error) error {
    15  	var firstErr error
    16  
    17  	for _, err := range errs {
    18  		if err == nil {
    19  			continue
    20  		}
    21  
    22  		resp, ok := httpgrpc.HTTPResponseFromError(err)
    23  		if !ok {
    24  			// Not a gRPC HTTP error, assume it is recoverable to fail gracefully.
    25  			return err
    26  		}
    27  		if resp.Code/100 == 5 || resp.Code == http.StatusTooManyRequests {
    28  			// Found a recoverable error, return it.
    29  			return err
    30  		} else if firstErr == nil {
    31  			firstErr = err
    32  		}
    33  	}
    34  
    35  	return firstErr
    36  }