Skip to content

Commit

Permalink
Merge pull request #4 from kodefluence/with-errors-in-jsonapi
Browse files Browse the repository at this point in the history
Create WithErrors method in jsonapi package
  • Loading branch information
insomnius authored Sep 4, 2022
2 parents 9e6b60a + 7644265 commit 17239a4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
24 changes: 24 additions & 0 deletions jsonapi/jsonapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 8 additions & 0 deletions jsonapi/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit 17239a4

Please sign in to comment.