Skip to content

Commit

Permalink
New JSON error facilities
Browse files Browse the repository at this point in the history
  • Loading branch information
manucorporat committed May 22, 2015
1 parent b7205a6 commit 71bd9f4
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
35 changes: 35 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package gin
import (
"bytes"
"fmt"
"reflect"
)

const (
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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 ""
Expand Down
5 changes: 3 additions & 2 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down

0 comments on commit 71bd9f4

Please sign in to comment.