-
Notifications
You must be signed in to change notification settings - Fork 0
/
gin.go
94 lines (78 loc) · 2.23 KB
/
gin.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package ginerrors
import (
"database/sql"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/spacetab-io/errors-go"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
validationErrorMessage = "validation error"
)
// Response makes common error response.
func Response(c *gin.Context, err interface{}) {
errCode, data := MakeResponse(err, getLang(c))
resp := errors.Response{Error: data}
c.AbortWithStatusJSON(errCode, resp)
}
// MakeResponse makes ErrorObject based on error type.
func MakeResponse(err interface{}, lang langName) (int, errors.ErrorObject) {
errObj := errors.ErrorObject{}
errCode := http.StatusBadRequest
errType := errors.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 = validationErrorMessage
errObj.Validation = makeErrorsSlice(et, lang)
case error:
st := status.Convert(et)
if st.Code() != codes.Unknown {
return MakeResponse(UnwrapRPCError(st), lang)
}
errCode, errObj.Message = getErrCode(et)
case string:
errObj.Message = et
case map[string]error:
msgs := make(map[string]string)
for k, e := range et {
msgs[k] = e.Error()
}
errObj.Message = msgs
}
errObj.Type = &errType
return errCode, errObj
}
func getErrCode(et error) (errCode int, msg string) {
msg = et.Error()
switch msg {
case ErrNotFound.Error():
errCode = http.StatusNotFound
case ErrNoMethod.Error():
errCode = http.StatusMethodNotAllowed
case ErrServerError.Error(), sql.ErrConnDone.Error(), sql.ErrTxDone.Error():
errCode = http.StatusInternalServerError
case ErrRecordNotFound.Error():
errCode = http.StatusNotFound
case sql.ErrNoRows.Error():
errCode = http.StatusNotFound
msg = ErrRecordNotFound.Error()
default:
errCode = http.StatusBadRequest
}
return
}