blob: 99673077b2b8cbe622fab291498630fe885e7282 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package responsewriters
18
19import (
20 "fmt"
21 "net/http"
22
23 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
24 "k8s.io/apimachinery/pkg/util/runtime"
25 "k8s.io/apiserver/pkg/storage"
26)
27
28// statusError is an object that can be converted into an metav1.Status
29type statusError interface {
30 Status() metav1.Status
31}
32
33// ErrorToAPIStatus converts an error to an metav1.Status object.
34func ErrorToAPIStatus(err error) *metav1.Status {
35 switch t := err.(type) {
36 case statusError:
37 status := t.Status()
38 if len(status.Status) == 0 {
39 status.Status = metav1.StatusFailure
40 }
41 if status.Code == 0 {
42 switch status.Status {
43 case metav1.StatusSuccess:
44 status.Code = http.StatusOK
45 case metav1.StatusFailure:
46 status.Code = http.StatusInternalServerError
47 }
48 }
49 status.Kind = "Status"
50 status.APIVersion = "v1"
51 //TODO: check for invalid responses
52 return &status
53 default:
54 status := http.StatusInternalServerError
55 switch {
56 //TODO: replace me with NewConflictErr
57 case storage.IsConflict(err):
58 status = http.StatusConflict
59 }
60 // Log errors that were not converted to an error status
61 // by REST storage - these typically indicate programmer
62 // error by not using pkg/api/errors, or unexpected failure
63 // cases.
64 runtime.HandleError(fmt.Errorf("apiserver received an error that is not an metav1.Status: %#+v", err))
65 return &metav1.Status{
66 TypeMeta: metav1.TypeMeta{
67 Kind: "Status",
68 APIVersion: "v1",
69 },
70 Status: metav1.StatusFailure,
71 Code: int32(status),
72 Reason: metav1.StatusReasonUnknown,
73 Message: err.Error(),
74 }
75 }
76}