From 71bd9f45002401ed29e0ba11789ac37b1c64e3c4 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Fri, 22 May 2015 04:43:43 +0200 Subject: [PATCH] New JSON error facilities --- errors.go | 35 +++++++++++++++++++++++++++++++++++ logger.go | 5 +++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/errors.go b/errors.go index 4aab56d2..af6b04a1 100644 --- a/errors.go +++ b/errors.go @@ -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 "" diff --git a/logger.go b/logger.go index bb7b2d15..5d54606e 100644 --- a/logger.go +++ b/logger.go @@ -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) } } }