Skip to content

Instantly share code, notes, and snippets.

@stokito
Created November 29, 2021 21:29
Show Gist options
  • Save stokito/78ba44dae8cac73cdf9d925bf416b2eb to your computer and use it in GitHub Desktop.
Save stokito/78ba44dae8cac73cdf9d925bf416b2eb to your computer and use it in GitHub Desktop.
GRPC catch error
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"reflect"
"strconv"
)
// GrpcError The interface the same as internal type Error from grpc: internal/status/status.go
type GrpcError interface {
GRPCStatus() *status.Status
Error() string
}
func main() {
// create a metric
metricApiError = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "api_error",
}, []string{"result"})
prometheus.Register(metricApiError)
err := yourGrpcReuqest(resp)
if err != nil {
grpcError, ok := err.(GrpcError)
if ok {
code := grpcError.GRPCStatus().Code()
// Unavailable: "the connection is draining" or "read: connection reset by peer"
timeoutErr := code == codes.DeadlineExceeded || code == codes.Unavailable
if timeoutErr {
Log.Printf("lookup timeout\n")
metricApiError.WithLabelValues("timeout").Inc()
return
}
errCode := strconv.Itoa(int(code))
Log.Printf("lookup error %s\n", bidReqId, err.Error())
metricApiError.WithLabelValues(errCode).Inc()
return
}
// unexpected error, probably never occurred
errMsg := err.Error()
errName := reflect.TypeOf(err).String()
Log.Printf("lookup unexpected error %s %s\n", errName, errMsg)
metricApiError.WithLabelValues(errName).Inc()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment