-
Notifications
You must be signed in to change notification settings - Fork 0
/
errorconverter.go
59 lines (51 loc) · 1.66 KB
/
errorconverter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package xgrpc
import (
"errors"
"github.com/go-playground/validator/v10"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net/http"
)
type HTTPStatusProvider interface {
HTTPStatus() int
}
// convertError converts errors to gRPC errors
func convertError(err error) error {
var statusProvider HTTPStatusProvider
if errors.As(err, &statusProvider) {
return convertWithHttpStatus(err, statusProvider)
}
var validationErr validator.FieldError
if errors.As(err, &validationErr) {
return status.Error(codes.InvalidArgument, err.Error())
}
var validationErrors validator.ValidationErrors
if errors.As(err, &validationErrors) {
return status.Error(codes.InvalidArgument, err.Error())
}
return err
}
func convertWithHttpStatus(err error, provider HTTPStatusProvider) error {
switch provider.HTTPStatus() {
case http.StatusBadRequest:
return status.Error(codes.InvalidArgument, err.Error())
case http.StatusUnauthorized:
return status.Error(codes.Unauthenticated, err.Error())
case http.StatusForbidden:
return status.Error(codes.PermissionDenied, err.Error())
case http.StatusNotFound:
return status.Error(codes.NotFound, err.Error())
case http.StatusConflict:
return status.Error(codes.AlreadyExists, err.Error())
case http.StatusUnprocessableEntity:
return status.Error(codes.InvalidArgument, err.Error())
case http.StatusTooManyRequests:
return status.Error(codes.ResourceExhausted, err.Error())
case http.StatusInternalServerError:
return status.Error(codes.Internal, err.Error())
case http.StatusServiceUnavailable:
return status.Error(codes.Unavailable, err.Error())
default:
return status.Error(codes.Unknown, err.Error())
}
}