Errors conforms to MarshalJSON interface

This commit is contained in:
Manu Mtz-Almeida 2015-05-22 18:34:42 +02:00
parent 9163ee543d
commit 4eeca21039
2 changed files with 17 additions and 1 deletions

View File

@ -6,6 +6,7 @@ package gin
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"reflect" "reflect"
) )
@ -60,6 +61,10 @@ func (msg *Error) JSON() interface{} {
return json return json
} }
func (msg *Error) MarshalJSON() ([]byte, error) {
return json.Marshal(msg.JSON())
}
func (msg *Error) Error() string { func (msg *Error) Error() string {
return msg.Err.Error() return msg.Err.Error()
} }
@ -113,6 +118,10 @@ func (a errorMsgs) JSON() interface{} {
} }
} }
func (a errorMsgs) MarshalJSON() ([]byte, error) {
return json.Marshal(a.JSON())
}
func (a errorMsgs) String() string { func (a errorMsgs) String() string {
if len(a) == 0 { if len(a) == 0 {
return "" return ""

View File

@ -5,6 +5,7 @@
package gin package gin
import ( import (
"encoding/json"
"errors" "errors"
"testing" "testing"
@ -30,6 +31,9 @@ func TestError(t *testing.T) {
"meta": "some data", "meta": "some data",
}) })
jsonBytes, _ := json.Marshal(err)
assert.Equal(t, string(jsonBytes), "{\"error\":\"test error\",\"meta\":\"some data\"}")
err.SetMeta(H{ err.SetMeta(H{
"status": "200", "status": "200",
"data": "some data", "data": "some data",
@ -77,11 +81,14 @@ Error #03: third
H{"error": "second", "meta": "some data"}, H{"error": "second", "meta": "some data"},
H{"error": "third", "status": "400"}, H{"error": "third", "status": "400"},
}) })
jsonBytes, _ := json.Marshal(errs)
assert.Equal(t, string(jsonBytes), "[{\"error\":\"first\"},{\"error\":\"second\",\"meta\":\"some data\"},{\"error\":\"third\",\"status\":\"400\"}]")
errs = errorMsgs{ errs = errorMsgs{
{Err: errors.New("first"), Type: ErrorTypePrivate}, {Err: errors.New("first"), Type: ErrorTypePrivate},
} }
assert.Equal(t, errs.JSON(), H{"error": "first"}) assert.Equal(t, errs.JSON(), H{"error": "first"})
jsonBytes, _ = json.Marshal(errs)
assert.Equal(t, string(jsonBytes), "{\"error\":\"first\"}")
errs = errorMsgs{} errs = errorMsgs{}
assert.Nil(t, errs.Last()) assert.Nil(t, errs.Last())