Skip to content

Commit

Permalink
fix: make apierror consistent (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
nrwiersma committed Oct 4, 2023
1 parent 822e0c9 commit 04390a0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
11 changes: 7 additions & 4 deletions http/render/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ const JSONContentType = "application/json"

// APIError contains error information that is rendered by JSONError.
type APIError struct {
Code int `json:"code"`
Reason string `json:"reason"`
// Code is the http status code.
Code int `json:"code"`

// Error is the reason for the error.
Error string `json:"error"`
}

// JSONInternalServerError writes a JSON internal server error.
Expand All @@ -33,10 +36,10 @@ func JSONError(rw http.ResponseWriter, code int, reason string) {
rw.Header().Set("Content-Type", JSONContentType)
rw.WriteHeader(code)

apiErr := APIError{Code: code, Reason: reason}
apiErr := APIError{Code: code, Error: reason}
b, err := jsoniter.Marshal(apiErr)
if err != nil {
_, _ = rw.Write([]byte(`{"reason":"Internal Server Error"}`))
_, _ = rw.Write([]byte(`{"code":500,"error":"internal server error"}`))
}

_, _ = rw.Write(b)
Expand Down
6 changes: 3 additions & 3 deletions http/render/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestJSONInternalServerError(t *testing.T) {

render.JSONInternalServerError(rec)

want := `{"code":500,"reason":"internal server error"}`
want := `{"code":500,"error":"internal server error"}`
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
assert.Equal(t, want, rec.Body.String())
Expand All @@ -26,7 +26,7 @@ func TestJSONErrorf(t *testing.T) {

render.JSONErrorf(rec, http.StatusBadRequest, "test %s", "message")

want := `{"code":400,"reason":"test message"}`
want := `{"code":400,"error":"test message"}`
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
assert.Equal(t, want, rec.Body.String())
Expand All @@ -37,7 +37,7 @@ func TestJSONError(t *testing.T) {

render.JSONError(rec, http.StatusBadRequest, "test message")

want := `{"code":400,"reason":"test message"}`
want := `{"code":400,"error":"test message"}`
assert.Equal(t, http.StatusBadRequest, rec.Code)
assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
assert.Equal(t, want, rec.Body.String())
Expand Down

0 comments on commit 04390a0

Please sign in to comment.