diff --git a/jsonapi/jsonapi_test.go b/jsonapi/jsonapi_test.go index bf47829..637aa7a 100644 --- a/jsonapi/jsonapi_test.go +++ b/jsonapi/jsonapi_test.go @@ -45,6 +45,30 @@ func TestJSONAPI(t *testing.T) { assert.Equal(t, "JSONAPI Error:\n[title] Detail: detail, Code: ERR401\n[title_2] Detail: detail_2, Code: ERR401\n", response.Errors.Error()) }) + t.Run("Nil data won't print in json format using WithErrors option", func(t *testing.T) { + response := jsonapi.BuildResponse( + jsonapi.WithException("ERR401", http.StatusNotFound, exception.Throw( + errors.New("unexpected error"), + exception.WithDetail("detail"), + exception.WithTitle("title"), + )), + jsonapi.WithExceptionMeta("ERR401", http.StatusNotFound, exception.Throw( + errors.New("unexpected error"), + exception.WithDetail("detail_2"), + exception.WithTitle("title_2"), + ), jsonapi.Meta{ + "sample": "sample", + }), + ) + + response2 := jsonapi.BuildResponse(jsonapi.WithErrors(response.Errors)) + + b, _ := json.Marshal(response2) + assert.Equal(t, "{\"errors\":[{\"title\":\"title\",\"detail\":\"detail\",\"code\":\"ERR401\",\"status\":404},{\"title\":\"title_2\",\"detail\":\"detail_2\",\"code\":\"ERR401\",\"status\":404,\"meta\":{\"sample\":\"sample\"}}]}", string(b)) + assert.Equal(t, http.StatusNotFound, response2.HTTPStatus()) + assert.Equal(t, "JSONAPI Error:\n[title] Detail: detail, Code: ERR401\n[title_2] Detail: detail_2, Code: ERR401\n", response2.Errors.Error()) + }) + t.Run("500 http status when error status not set", func(t *testing.T) { response := jsonapi.BuildResponse( jsonapi.WithException("ERR401", 0, exception.Throw( diff --git a/jsonapi/option.go b/jsonapi/option.go index 09c0b01..8982e96 100644 --- a/jsonapi/option.go +++ b/jsonapi/option.go @@ -10,6 +10,14 @@ func WithData(data interface{}) Option { } } +func WithErrors(errors Errors) Option { + return func(b *Body) { + if errors != nil { + b.Errors = errors + } + } +} + func WithException(code string, status int, exc exception.Exception) Option { return WithExceptionMeta(code, status, exc, nil) }