github.com/lingyao2333/mo-zero@v1.4.1/rest/internal/errcode/grpc.go (about)

     1  package errcode
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"google.golang.org/grpc/codes"
     7  	"google.golang.org/grpc/status"
     8  )
     9  
    10  // CodeFromGrpcError converts the gRPC error to an HTTP status code.
    11  // See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
    12  func CodeFromGrpcError(err error) int {
    13  	code := status.Code(err)
    14  	switch code {
    15  	case codes.OK:
    16  		return http.StatusOK
    17  	case codes.InvalidArgument, codes.FailedPrecondition, codes.OutOfRange:
    18  		return http.StatusBadRequest
    19  	case codes.Unauthenticated:
    20  		return http.StatusUnauthorized
    21  	case codes.PermissionDenied:
    22  		return http.StatusForbidden
    23  	case codes.NotFound:
    24  		return http.StatusNotFound
    25  	case codes.Canceled:
    26  		return http.StatusRequestTimeout
    27  	case codes.AlreadyExists, codes.Aborted:
    28  		return http.StatusConflict
    29  	case codes.ResourceExhausted:
    30  		return http.StatusTooManyRequests
    31  	case codes.Internal, codes.DataLoss, codes.Unknown:
    32  		return http.StatusInternalServerError
    33  	case codes.Unimplemented:
    34  		return http.StatusNotImplemented
    35  	case codes.Unavailable:
    36  		return http.StatusServiceUnavailable
    37  	case codes.DeadlineExceeded:
    38  		return http.StatusGatewayTimeout
    39  	}
    40  
    41  	return http.StatusInternalServerError
    42  }
    43  
    44  // IsGrpcError checks if the error is a gRPC error.
    45  func IsGrpcError(err error) bool {
    46  	if err == nil {
    47  		return false
    48  	}
    49  
    50  	_, ok := err.(interface {
    51  		GRPCStatus() *status.Status
    52  	})
    53  
    54  	return ok
    55  }