Rename WriteErrorResponse() to simply ErrorJSON() and reorder arguments
This way we better mimic net/http.Error() https://pkg.go.dev/net/http?tab=doc#Error
This commit is contained in:
@@ -10,13 +10,15 @@ type ServerErrMessage struct {
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// WriteErrorResponse writes the error JSON body to the provided http.ResponseWriter,
|
||||
// after setting the appropiate Content-Type header
|
||||
func WriteErrorResponse(statusCode int, reasonMsg string, res http.ResponseWriter) {
|
||||
respBody := ServerErrMessage{}
|
||||
respBody.Reason = reasonMsg
|
||||
bb, _ := json.Marshal(respBody)
|
||||
res.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
res.WriteHeader(statusCode)
|
||||
_, _ = res.Write(bb)
|
||||
// ErrorJSON writes the provided error as a JSON body to the provided
|
||||
// http.ResponseWriter, after setting the appropriate Content-Type header
|
||||
func ErrorJSON(w http.ResponseWriter, error string, code int) {
|
||||
body, _ := json.Marshal(
|
||||
ServerErrMessage{
|
||||
Reason: error,
|
||||
},
|
||||
)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
|
||||
@@ -10,31 +10,31 @@ import (
|
||||
"github.com/BBVA/kapow/internal/server/srverrors"
|
||||
)
|
||||
|
||||
func TestWriteErrorResponseSetsAppJsonContentType(t *testing.T) {
|
||||
func TestErrorJSONSetsAppJsonContentType(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srverrors.WriteErrorResponse(0, "Not Important Here", w)
|
||||
srverrors.ErrorJSON(w, "Not Important Here", 0)
|
||||
|
||||
if v := w.Result().Header.Get("Content-Type"); v != "application/json; charset=utf-8" {
|
||||
t.Errorf("Content-Type header mismatch. Expected: %q, got: %q", "application/json; charset=utf-8", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErrorResponseSetsRequestedStatusCode(t *testing.T) {
|
||||
func TestErrorJSONSetsRequestedStatusCode(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srverrors.WriteErrorResponse(http.StatusGone, "Not Important Here", w)
|
||||
srverrors.ErrorJSON(w, "Not Important Here", http.StatusGone)
|
||||
|
||||
if v := w.Result().StatusCode; v != http.StatusGone {
|
||||
t.Errorf("Status code mismatch. Expected: %d, got: %d", http.StatusGone, v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErrorResponseSetsBodyCorrectly(t *testing.T) {
|
||||
func TestErrorJSONSetsBodyCorrectly(t *testing.T) {
|
||||
expectedReason := "Something Not Found"
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srverrors.WriteErrorResponse(http.StatusNotFound, expectedReason, w)
|
||||
srverrors.ErrorJSON(w, expectedReason, http.StatusNotFound)
|
||||
|
||||
errMsg := srverrors.ServerErrMessage{}
|
||||
if bodyBytes, err := ioutil.ReadAll(w.Result().Body); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user