2019-06-03 18:44:43 +01:00
|
|
|
package grpc
|
|
|
|
|
|
|
|
import (
|
2021-10-12 12:55:53 +01:00
|
|
|
"go-micro.dev/v4/errors"
|
2021-08-12 14:15:49 +03:00
|
|
|
"google.golang.org/grpc/codes"
|
2019-06-03 18:44:43 +01:00
|
|
|
"google.golang.org/grpc/status"
|
2021-08-12 14:15:49 +03:00
|
|
|
"net/http"
|
2019-06-03 18:44:43 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func microError(err error) error {
|
|
|
|
// no error
|
|
|
|
switch err {
|
|
|
|
case nil:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-06 13:18:33 +03:00
|
|
|
if verr, ok := err.(*errors.Error); ok {
|
|
|
|
return verr
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// grpc error
|
2020-03-17 14:27:20 +03:00
|
|
|
s, ok := status.FromError(err)
|
|
|
|
if !ok {
|
|
|
|
return err
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
2020-03-17 14:27:20 +03:00
|
|
|
// return first error from details
|
|
|
|
if details := s.Details(); len(details) > 0 {
|
|
|
|
return microError(details[0].(error))
|
|
|
|
}
|
|
|
|
|
|
|
|
// try to decode micro *errors.Error
|
|
|
|
if e := errors.Parse(s.Message()); e.Code > 0 {
|
|
|
|
return e // actually a micro error
|
|
|
|
}
|
|
|
|
|
|
|
|
// fallback
|
2021-08-12 14:15:49 +03:00
|
|
|
return errors.New("go.micro.client", s.Message(), microStatusFromGrpcCode(s.Code()))
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
2021-08-12 14:15:49 +03:00
|
|
|
|
|
|
|
func microStatusFromGrpcCode(code codes.Code) int32 {
|
|
|
|
switch code {
|
|
|
|
case codes.OK:
|
|
|
|
return http.StatusOK
|
|
|
|
case codes.InvalidArgument:
|
|
|
|
return http.StatusBadRequest
|
|
|
|
case codes.DeadlineExceeded:
|
|
|
|
return http.StatusRequestTimeout
|
|
|
|
case codes.NotFound:
|
|
|
|
return http.StatusNotFound
|
|
|
|
case codes.AlreadyExists:
|
|
|
|
return http.StatusConflict
|
|
|
|
case codes.PermissionDenied:
|
|
|
|
return http.StatusForbidden
|
|
|
|
case codes.Unauthenticated:
|
|
|
|
return http.StatusUnauthorized
|
|
|
|
case codes.FailedPrecondition:
|
|
|
|
return http.StatusPreconditionFailed
|
|
|
|
case codes.Unimplemented:
|
|
|
|
return http.StatusNotImplemented
|
|
|
|
case codes.Internal:
|
|
|
|
return http.StatusInternalServerError
|
|
|
|
case codes.Unavailable:
|
|
|
|
return http.StatusServiceUnavailable
|
|
|
|
}
|
|
|
|
|
|
|
|
return http.StatusInternalServerError
|
|
|
|
}
|