diff --git a/request.go b/request.go index e73a571..19294a0 100644 --- a/request.go +++ b/request.go @@ -66,7 +66,13 @@ func UnmarshalPayload(in io.Reader, model interface{}) error { } -func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node) error { +func unmarshalNode(data *Node, model reflect.Value, included *map[string]*Node) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("data is not a jsonapi representation of '%v'", model.Type()) + } + }() + modelValue := model.Elem() modelType := model.Type().Elem() diff --git a/request_test.go b/request_test.go index f96d805..4f22d2a 100644 --- a/request_test.go +++ b/request_test.go @@ -3,7 +3,10 @@ package jsonapi import ( "bytes" "encoding/json" + "fmt" "io" + "regexp" + "strings" "testing" "time" ) @@ -12,6 +15,32 @@ type BadModel struct { Id int `jsonapi:"primary"` } +func TestMalformedTag(t *testing.T) { + out := new(BadModel) + err := UnmarshalPayload(samplePayload(), out) + if err == nil { + t.Fatalf("Did not error out with wrong number of arguments in tag") + } + + fmt.Println(err.Error()) + r := regexp.MustCompile(`too few arguments`) + + if !r.Match([]byte(err.Error())) { + t.Fatalf("The err was not due too few arguments in a tag") + } +} + +func TestUnmarshalInvalidJSON(t *testing.T) { + in := strings.NewReader("{}") + out := new(Blog) + + err := UnmarshalPayload(in, out) + + if err == nil { + t.Fatalf("Did not error out the invalid JSON.") + } +} + func TestUnmarshalSetsId(t *testing.T) { in := samplePayloadWithId() out := new(Blog)