From 72124cad19c1669c45c9562169ad5ec2a00bda17 Mon Sep 17 00:00:00 2001 From: Andrea Masi Date: Sun, 12 Aug 2018 11:49:34 +0200 Subject: [PATCH] Implement source in error object --- errors.go | 13 +++++++++++++ errors_test.go | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/errors.go b/errors.go index ed7fa9f..897be86 100644 --- a/errors.go +++ b/errors.go @@ -23,6 +23,16 @@ type ErrorsPayload struct { Errors []*ErrorObject `json:"errors"` } +// ErrorObject implements the JSON API `source` object (http://jsonapi.org/format/#error-objects). +type ErrorSource struct { + // If the error comes from validating data from a client, + // this is the `path` of the attribute that has generated the error. + // es. `/data/attributes/email`. + Pointer string `json:"pointer,omitempty"` + // A string indicating which URI query parameter caused the error. + Parameter string `json:"parameter,omitempty"` +} + // ErrorObject is an `Error` implementation as well as an implementation of the JSON API error object. // // The main idea behind this struct is that you can use it directly in your code as an error type @@ -47,6 +57,9 @@ type ErrorObject struct { // Meta is an object containing non-standard meta-information about the error. Meta *map[string]interface{} `json:"meta,omitempty"` + + // Source contains reference to the source of the error. + Source *ErrorSource `json:"source,omitempty"` } // Error implements the `Error` interface. diff --git a/errors_test.go b/errors_test.go index 683a1d1..7900b72 100644 --- a/errors_test.go +++ b/errors_test.go @@ -40,6 +40,13 @@ func TestMarshalErrorsWritesTheExpectedPayload(t *testing.T) { map[string]interface{}{"title": "Test title.", "detail": "Test detail", "meta": map[string]interface{}{"key": "val"}}, }}, }, + { + Title: "TestSourceFieldIsSerializedProperly", + In: []*ErrorObject{{Source: &ErrorSource{Pointer: "/data/attributes/email", Parameter: "email"}}}, + Out: map[string]interface{}{"errors": []interface{}{ + map[string]interface{}{"source": map[string]interface{}{"pointer": "/data/attributes/email", "parameter": "email"}}, + }}, + }, } for _, testRow := range marshalErrorsTableTasts { t.Run(testRow.Title, func(t *testing.T) {