Skip to content

Commit

Permalink
Merge pull request #1 from zeroabe/feature/grpc_errors
Browse files Browse the repository at this point in the history
grpc errors
  • Loading branch information
smgladkovskiy authored May 17, 2020
2 parents 392f269 + 20aa783 commit 51cd3f3
Show file tree
Hide file tree
Showing 6 changed files with 255 additions and 4 deletions.
21 changes: 17 additions & 4 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@ import (
"strings"

"github.com/gin-gonic/gin"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/go-playground/validator.v9"

errs "github.com/microparts/errors-go"
)

const (
validationErrorMessage = "validation error"
)

//Response makes common error response
func Response(c *gin.Context, err interface{}) {
errCode, data := MakeResponse(err, getLang(c))
Expand All @@ -25,23 +31,30 @@ func MakeResponse(err interface{}, lang langName) (int, *errs.ErrorObject) {
errType := errs.ErrorTypeError

switch et := err.(type) {
case GRPCValidationError:
errCode = http.StatusUnprocessableEntity

errObj.Message = validationErrorMessage
errObj.Validation = makeErrorsSliceFromViolations(et.Violations)
case []error:
errCode = http.StatusInternalServerError
msgs := make([]string, 0)
for _, e := range err.([]error) {
msgs = append(msgs, e.Error())
}
errObj.Message = strings.Join(msgs, "; ")

case validator.ValidationErrors:
errCode = http.StatusUnprocessableEntity

errObj.Message = "validation error"
errObj.Message = validationErrorMessage
errObj.Validation = makeErrorsSlice(et, lang)

case error:
errCode, errObj.Message = getErrCode(et)
st := status.Convert(et)
if st.Code() != codes.Unknown {
return MakeResponse(UnwrapRPCError(st), lang)
}

errCode, errObj.Message = getErrCode(et)
case map[string]error:
msgs := make(map[string]string)
for k, e := range et {
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@ require (
github.com/gin-gonic/gin v1.4.1-0.20191002234641-4fd3234840db
github.com/microparts/errors-go v1.1.1
github.com/stretchr/testify v1.4.0
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55
google.golang.org/grpc v1.29.1
gopkg.in/go-playground/validator.v9 v9.30.0
)
50 changes: 50 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.4.1-0.20191002234641-4fd3234840db h1:pbCWxsnOJV2VvzC5tEncCW3YLzmP7eb6CvKP69Zoeas=
Expand All @@ -9,8 +17,15 @@ github.com/go-playground/locales v0.12.1 h1:2FITxuFt/xuCNP1Acdhv62OzaCiviiE4kotf
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
github.com/go-playground/universal-translator v0.16.0 h1:X++omBR/4cE2MNg91AoC3rmGrCjJ8eAeUP/K/EKx4DM=
github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
Expand All @@ -26,6 +41,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLD
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
Expand All @@ -34,8 +50,40 @@ github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.29.1 h1:EC2SB8S04d2r73uptxphDSUG+kTKVgjRPF+N3xpxRB4=
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM=
Expand All @@ -45,3 +93,5 @@ gopkg.in/go-playground/validator.v9 v9.30.0 h1:Wk0Z37oBmKj9/n+tPyBHZmeL19LaCoK3Q
gopkg.in/go-playground/validator.v9 v9.30.0/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
106 changes: 106 additions & 0 deletions grpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package ginerrors

import (
"errors"
"net/http"

"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/go-playground/validator.v9"
)

type GRPCValidationError struct {
Violations []*errdetails.BadRequest_FieldViolation
}

var (
httpToGRPCCodes = map[int]codes.Code{
http.StatusNotFound: codes.NotFound,
http.StatusMethodNotAllowed: codes.Unavailable,
http.StatusInternalServerError: codes.Internal,
http.StatusBadRequest: codes.InvalidArgument,
}

grpcToHTTPCodes = map[codes.Code]int{
codes.NotFound: http.StatusNotFound,
codes.Unavailable: http.StatusMethodNotAllowed,
codes.Internal: http.StatusInternalServerError,
codes.InvalidArgument: http.StatusBadRequest,
}
)

func UnwrapRPCError(st *status.Status) interface{} {
switch st.Code() {
case codes.NotFound:
return ErrRecordNotFound
case codes.Unavailable:
return ErrNoMethod
case codes.Internal:
return ErrServerError
case codes.InvalidArgument:
details := st.Details()
violations := getViolations(details)

return GRPCValidationError{Violations: violations}
default:
return errors.New(st.Message())
}
}

func WrapErrorWithStatus(err error, lang string) error {
l := langName(lang)
httpCode, msg := getErrCode(err)

code, ok := getGRPCCode(httpCode)
if !ok {
return err
}

st := status.New(code, msg)

if code == codes.InvalidArgument {
if errs, ok := err.(validator.ValidationErrors); ok {
var e error
br := &errdetails.BadRequest{}
for _, ee := range errs {
field := getFieldName(ee.Namespace(), ee.Field())
msg := getErrMessage(validationRule(ee.ActualTag()), field, ee.Param(), l)
violation := &errdetails.BadRequest_FieldViolation{
Field: string(field),
Description: string(msg),
}

br.FieldViolations = append(br.FieldViolations, violation)
}

st, e = st.WithDetails(br)
if e != nil {
return err
}
}
}

return st.Err()
}

// getGRPCCode returns grpc error code by first value and its existence by second
func getGRPCCode(httpCode int) (codes.Code, bool) {
c, ok := httpToGRPCCodes[httpCode]
return c, ok
}

func getViolations(details []interface{}) []*errdetails.BadRequest_FieldViolation {
if len(details) == 0 {
return nil
}

violations := make([]*errdetails.BadRequest_FieldViolation, 0)
for _, detail := range details {
if d, ok := detail.(*errdetails.BadRequest); ok {
violations = append(violations, d.FieldViolations...)
}
}

return violations
}
51 changes: 51 additions & 0 deletions grpc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package ginerrors

import (
"database/sql"
"errors"
"testing"

"github.com/stretchr/testify/assert"
)

const (
unknownErrMessage = "rpc error: code = InvalidArgument desc = foo"
unknownErrValue = "foo"
recordNotFountMessage = "rpc error: code = NotFound desc = record not found"
unavailableMethodMessage = "rpc error: code = Unavailable desc = method not allowed"
)

func TestWrapErrWithRPC(t *testing.T) {
cases := []struct {
caseName string
err error
lang string
expected string
}{
{
caseName: "unknown err",
err: errors.New(unknownErrValue),
lang: "en",
expected: unknownErrMessage,
},
{
caseName: "sql err",
err: sql.ErrNoRows,
lang: "en",
expected: recordNotFountMessage,
},
{
caseName: "unavailable method",
err: ErrNoMethod,
lang: "en",
expected: unavailableMethodMessage,
},
}
for _, cc := range cases {
t.Run(cc.caseName, func(t *testing.T) {
err := WrapErrorWithStatus(cc.err, cc.lang)
assert.Error(t, err)
assert.Equal(t, cc.expected, err.Error())
})
}
}
29 changes: 29 additions & 0 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"

"github.com/gin-gonic/gin"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"gopkg.in/go-playground/validator.v9"

errs "github.com/microparts/errors-go"
Expand All @@ -26,6 +27,16 @@ var CommonValidationErrors = map[langName]validationErrors{
"required": "Свойство `%s` обязательно для заполнения",
"gt": "Свойство `%s` должно содержать более `%s` элементов",
},
"en": {
"ek": "Fail to validate field `%s` with rule `%s`",
"required": "Field `%s` is required",
"gt": "Field `%s` must contain more than `%s` elements",
},
"es": {
"ek": "",
"required": "",
"gt": "",
},
}

var (
Expand Down Expand Up @@ -61,6 +72,24 @@ func makeErrorsSlice(err error, lang langName) map[errs.FieldName][]errs.Validat
}
return ve
}

func makeErrorsSliceFromViolations(violations []*errdetails.BadRequest_FieldViolation) map[errs.FieldName][]errs.ValidationError {
ve := make(map[errs.FieldName][]errs.ValidationError)
for _, v := range violations {
if v == nil {
continue
}
field := errs.FieldName(v.Field)
if _, ok := ve[field]; !ok {
ve[field] = make([]errs.ValidationError, 0)
}
e := errs.ValidationError(v.Description)
ve[field] = append(ve[field], e)
}

return ve
}

func getFieldName(namespace string, field string) errs.FieldName {
namespace = strings.Replace(namespace, "]", "", -1)
namespace = strings.Replace(namespace, "[", ".", -1)
Expand Down

0 comments on commit 51cd3f3

Please sign in to comment.