Browse Source

Errors conforms to MarshalJSON interface

Manu Mtz-Almeida 10 years ago
parent
commit
4eeca21039
2 changed files with 17 additions and 1 deletions
  1. 9 0
      errors.go
  2. 8 1
      errors_test.go

+ 9 - 0
errors.go

@@ -6,6 +6,7 @@ package gin
 
 import (
 	"bytes"
+	"encoding/json"
 	"fmt"
 	"reflect"
 )
@@ -60,6 +61,10 @@ func (msg *Error) JSON() interface{} {
 	return json
 }
 
+func (msg *Error) MarshalJSON() ([]byte, error) {
+	return json.Marshal(msg.JSON())
+}
+
 func (msg *Error) Error() string {
 	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 {
 	if len(a) == 0 {
 		return ""

+ 8 - 1
errors_test.go

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