-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
apierror.go
61 lines (48 loc) · 1.2 KB
/
apierror.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package api
import (
"fmt"
"net/http"
"github.com/go-openapi/runtime"
"github.com/cilium/cilium/api/v1/models"
)
// APIError is the error representation for the API.
type APIError struct {
code int
msg string
}
// New creates a API error from the code, msg and extra arguments.
func New(code int, msg string, args ...interface{}) *APIError {
if code <= 0 {
code = 500
}
if len(args) > 0 {
return &APIError{code: code, msg: fmt.Sprintf(msg, args...)}
}
return &APIError{code: code, msg: msg}
}
// Error creates a new API error from the code and error.
func Error(code int, err error) *APIError {
if err == nil {
err = fmt.Errorf("Error pointer was nil")
}
return New(code, err.Error())
}
// Error returns the API error message.
func (a *APIError) Error() string {
return a.msg
}
// GetModel returns model error.
func (a *APIError) GetModel() *models.Error {
m := models.Error(a.msg)
return &m
}
// WriteResponse to the client.
func (a *APIError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(a.code)
m := a.GetModel()
if err := producer.Produce(rw, m); err != nil {
panic(err)
}
}