1 // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2 // Use of this source code is governed by a MIT style
3 // license that can be found in the LICENSE file.
12 "github.com/gin-gonic/gin/json"
18 ErrorTypeBind ErrorType = 1 << 63 // used when c.Bind() fails
19 ErrorTypeRender ErrorType = 1 << 62 // used when c.Render() fails
20 ErrorTypePrivate ErrorType = 1 << 0
21 ErrorTypePublic ErrorType = 1 << 1
23 ErrorTypeAny ErrorType = 1<<64 - 1
33 type errorMsgs []*Error
35 var _ error = &Error{}
37 func (msg *Error) SetType(flags ErrorType) *Error {
42 func (msg *Error) SetMeta(data interface{}) *Error {
47 func (msg *Error) JSON() interface{} {
50 value := reflect.ValueOf(msg.Meta)
55 for _, key := range value.MapKeys() {
56 json[key.String()] = value.MapIndex(key).Interface()
59 json["meta"] = msg.Meta
62 if _, ok := json["error"]; !ok {
63 json["error"] = msg.Error()
68 // MarshalJSON implements the json.Marshaller interface.
69 func (msg *Error) MarshalJSON() ([]byte, error) {
70 return json.Marshal(msg.JSON())
73 // Error implements the error interface
74 func (msg Error) Error() string {
75 return msg.Err.Error()
78 func (msg *Error) IsType(flags ErrorType) bool {
79 return (msg.Type & flags) > 0
82 // ByType returns a readonly copy filtered the byte.
83 // ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic.
84 func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
88 if typ == ErrorTypeAny {
92 for _, msg := range a {
94 result = append(result, msg)
100 // Last returns the last error in the slice. It returns nil if the array is empty.
101 // Shortcut for errors[len(errors)-1].
102 func (a errorMsgs) Last() *Error {
103 if length := len(a); length > 0 {
109 // Errors returns an array will all the error messages.
111 // c.Error(errors.New("first"))
112 // c.Error(errors.New("second"))
113 // c.Error(errors.New("third"))
114 // c.Errors.Errors() // == []string{"first", "second", "third"}
115 func (a errorMsgs) Errors() []string {
119 errorStrings := make([]string, len(a))
120 for i, err := range a {
121 errorStrings[i] = err.Error()
126 func (a errorMsgs) JSON() interface{} {
131 return a.Last().JSON()
133 json := make([]interface{}, len(a))
134 for i, err := range a {
141 func (a errorMsgs) MarshalJSON() ([]byte, error) {
142 return json.Marshal(a.JSON())
145 func (a errorMsgs) String() string {
149 var buffer bytes.Buffer
150 for i, msg := range a {
151 fmt.Fprintf(&buffer, "Error #%02d: %s\n", i+1, msg.Err)
153 fmt.Fprintf(&buffer, " Meta: %v\n", msg.Meta)
156 return buffer.String()