New JSON error facilities

This commit is contained in:
Manu Mtz-Almeida 2015-05-22 04:43:43 +02:00
parent b7205a6ec2
commit 71bd9f4500
2 changed files with 38 additions and 2 deletions

View File

@ -7,6 +7,7 @@ package gin
import (
"bytes"
"fmt"
"reflect"
)
const (
@ -36,6 +37,25 @@ func (msg *errorMsg) Meta(data interface{}) *errorMsg {
return msg
}
func (msg *errorMsg) JSON() interface{} {
json := H{}
if msg.Metadata != nil {
value := reflect.ValueOf(msg.Metadata)
switch value.Kind() {
case reflect.Struct:
return msg.Metadata
case reflect.Map:
for _, key := range value.MapKeys() {
json[key.String()] = value.MapIndex(key).Interface()
}
}
}
if _, ok := json["error"]; !ok {
json["error"] = msg.Error()
}
return json
}
func (msg *errorMsg) Error() string {
return msg.Err.Error()
}
@ -74,6 +94,21 @@ func (a errorMsgs) Errors() []string {
return errorStrings
}
func (a errorMsgs) JSON() interface{} {
switch len(a) {
case 0:
return nil
case 1:
return a.Last().JSON()
default:
json := make([]interface{}, len(a))
for i, err := range a {
json[i] = err.JSON()
}
return json
}
}
func (a errorMsgs) String() string {
if len(a) == 0 {
return ""

View File

@ -30,8 +30,9 @@ func ErrorLoggerT(typ int) HandlerFunc {
c.Next()
if !c.Writer.Written() {
if errs := c.Errors.ByType(typ); len(errs) > 0 {
c.JSON(-1, errs.Errors())
json := c.Errors.ByType(typ).JSON()
if json != nil {
c.JSON(-1, json)
}
}
}