...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package utils
17
18 import (
19 "fmt"
20 "net/http"
21 "strings"
22
23 "github.com/gin-gonic/gin"
24 "github.com/joomcode/errorx"
25 apierrors "k8s.io/apimachinery/pkg/api/errors"
26 )
27
28 var (
29 ErrNS = errorx.NewNamespace("error.api")
30 ErrUnknown = ErrNS.NewType("unknown")
31 ErrBadRequest = ErrNS.NewType("bad_request")
32 ErrNotFound = ErrNS.NewType("resource_not_found")
33 ErrInternalServer = ErrNS.NewType("internal_server_error")
34
35 ErrNoClusterPrivilege = ErrNS.NewType("no_cluster_privilege")
36 ErrNoNamespacePrivilege = ErrNS.NewType("no_namespace_privilege")
37 )
38
39 type APIError struct {
40 Code int `json:"code"`
41 Type string `json:"type"`
42 Message string `json:"message"`
43 FullText string `json:"full_text"`
44 }
45
46 func SetAPIError(c *gin.Context, err *errorx.Error) {
47 typeName := errorx.GetTypeName(err)
48
49 var code int
50 switch typeName {
51 case ErrBadRequest.FullName():
52 code = http.StatusBadRequest
53 case ErrNoClusterPrivilege.FullName(), ErrNoNamespacePrivilege.FullName():
54 code = http.StatusUnauthorized
55 case ErrNotFound.FullName():
56 code = http.StatusNotFound
57 case ErrUnknown.FullName(), ErrInternalServer.FullName():
58 code = http.StatusInternalServerError
59 default:
60 code = http.StatusInternalServerError
61 }
62
63 apiError := APIError{
64 Code: code,
65 Type: typeName,
66 Message: err.Error(),
67 FullText: fmt.Sprintf("%+v", err),
68 }
69
70 Log.Error(err.Cause(), typeName)
71 c.AbortWithStatusJSON(code, &apiError)
72 }
73
74 func SetAPImachineryError(c *gin.Context, err error) {
75 if apierrors.IsForbidden(err) && strings.Contains(err.Error(), "at the cluster scope") {
76 SetAPIError(c, ErrNoClusterPrivilege.WrapWithNoMessage(err))
77
78 return
79 } else if apierrors.IsForbidden(err) && strings.Contains(err.Error(), "in the namespace") {
80 SetAPIError(c, ErrNoNamespacePrivilege.WrapWithNoMessage(err))
81
82 return
83 } else if apierrors.IsNotFound(err) {
84 SetAPIError(c, ErrNotFound.WrapWithNoMessage(err))
85
86 return
87 }
88
89 SetAPIError(c, ErrInternalServer.WrapWithNoMessage(err))
90 }
91