-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
95 lines (91 loc) · 2.74 KB
/
errors.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
95
package main
import (
"encoding/json"
"fmt"
"github.com/go-playground/form/v4"
"github.com/go-playground/validator/v10"
"net/http"
"reflect"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// NewBindingError returns an error indicating the request is invalid and cannot be bound to an object.
func NewBindingError(err error, obj interface{}) *apierrors.StatusError {
if err == nil {
return &apierrors.StatusError{metav1.Status{
Status: metav1.StatusSuccess,
Code: http.StatusNoContent,
}}
}
switch t := err.(type) {
case *validator.InvalidValidationError:
return &apierrors.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusUnprocessableEntity,
Reason: metav1.StatusReasonInvalid,
//Details: &metav1.StatusDetails{
// Group: qualifiedKind.Group,
// Kind: qualifiedKind.Kind,
// Name: name,
// Causes: causes,
//},
Message: err.Error(),
}}
case validator.ValidationErrors:
causes := make([]metav1.StatusCause, 0, len(t))
for i := range t {
err := t[i]
st := metav1.CauseTypeFieldValueInvalid
if err.Tag() == "required" {
st = metav1.CauseTypeFieldValueRequired
}
causes = append(causes, metav1.StatusCause{
Type: st,
Message: err.Error(),
Field: err.Namespace(),
})
}
return &apierrors.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusUnprocessableEntity,
Reason: metav1.StatusReasonInvalid,
Details: &metav1.StatusDetails{
//Group: qualifiedKind.Group,
//Kind: qualifiedKind.Kind,
//Name: name,
Causes: causes,
},
// Message: fmt.Sprintf("%s %q is invalid: %v", qualifiedKind.String(), name, errs.ToAggregate()),
Message: fmt.Sprintf("%s is invalid", reflect.TypeOf(obj)),
}}
case form.DecodeErrors:
ot := reflect.TypeOf(obj)
if ot.Kind() == reflect.Interface {
ot = ot.Elem()
}
causes := make([]metav1.StatusCause, 0, len(t))
for field, err := range t {
causes = append(causes, metav1.StatusCause{
Type: metav1.CauseTypeFieldValueInvalid,
Message: err.Error(),
Field: field,
})
}
return &apierrors.StatusError{metav1.Status{
Status: metav1.StatusFailure,
Code: http.StatusBadRequest,
Reason: metav1.StatusReasonBadRequest,
Details: &metav1.StatusDetails{
// Group: qualifiedKind.Group,
//Kind: qualifiedKind.Kind,
//Name: name,
Causes: causes,
},
Message: fmt.Sprintf("failed to decode into %s", reflect.TypeOf(obj)),
}}
case *form.InvalidDecoderError, *json.InvalidUnmarshalError:
return apierrors.NewInternalError(err) // error due to bug in source code
default:
return apierrors.NewBadRequest(err.Error()) // error due to bad input from request body
}
}