Errors conforms to MarshalJSON interface
This commit is contained in:
		@ -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 ""
 | 
			
		||||
 | 
			
		||||
@ -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())
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user