go-micro.dev/v5@v5.12.0/client/grpc/error.go (about)

     1  package grpc
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"go-micro.dev/v5/errors"
     7  	"google.golang.org/grpc/codes"
     8  	"google.golang.org/grpc/status"
     9  )
    10  
    11  func microError(err error) error {
    12  	// no error
    13  	switch err {
    14  	case nil:
    15  		return nil
    16  	}
    17  
    18  	if verr, ok := err.(*errors.Error); ok {
    19  		return verr
    20  	}
    21  
    22  	// grpc error
    23  	s, ok := status.FromError(err)
    24  	if !ok {
    25  		return err
    26  	}
    27  
    28  	// return first error from details
    29  	if details := s.Details(); len(details) > 0 {
    30  		return microError(details[0].(error))
    31  	}
    32  
    33  	// try to decode micro *errors.Error
    34  	if e := errors.Parse(s.Message()); e.Code > 0 {
    35  		return e // actually a micro error
    36  	}
    37  
    38  	// fallback
    39  	return errors.New("go.micro.client", s.Message(), microStatusFromGrpcCode(s.Code()))
    40  }
    41  
    42  func microStatusFromGrpcCode(code codes.Code) int32 {
    43  	switch code {
    44  	case codes.OK:
    45  		return http.StatusOK
    46  	case codes.InvalidArgument:
    47  		return http.StatusBadRequest
    48  	case codes.DeadlineExceeded:
    49  		return http.StatusRequestTimeout
    50  	case codes.NotFound:
    51  		return http.StatusNotFound
    52  	case codes.AlreadyExists:
    53  		return http.StatusConflict
    54  	case codes.PermissionDenied:
    55  		return http.StatusForbidden
    56  	case codes.Unauthenticated:
    57  		return http.StatusUnauthorized
    58  	case codes.FailedPrecondition:
    59  		return http.StatusPreconditionFailed
    60  	case codes.Unimplemented:
    61  		return http.StatusNotImplemented
    62  	case codes.Internal:
    63  		return http.StatusInternalServerError
    64  	case codes.Unavailable:
    65  		return http.StatusServiceUnavailable
    66  	}
    67  
    68  	return http.StatusInternalServerError
    69  }