Better error responses

This commit is contained in:
MrLetsplay 2023-08-18 22:43:07 +02:00
parent 84b877017c
commit 13a199afee
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg

31
main.go
View File

@ -22,14 +22,29 @@ type Note struct {
func httpError(err error, statusCode int, message string, w http.ResponseWriter) bool { func httpError(err error, statusCode int, message string, w http.ResponseWriter) bool {
if err != nil { if err != nil {
log.Println(err) log.Println(err)
w.WriteHeader(statusCode) writeError(w, statusCode, message)
io.WriteString(w, message)
return true return true
} }
return false return false
} }
func writeError(w http.ResponseWriter, statusCode int, message string) {
type errorResponse struct {
Message string `json:"message"`
}
response := errorResponse{Message: message}
json, err := json.Marshal(response)
if err != nil {
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write(json)
}
func getNotes(w http.ResponseWriter, req *http.Request, _ httprouter.Params) { func getNotes(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
res, err := db.Query(`SELECT Id, Content FROM Notes`) res, err := db.Query(`SELECT Id, Content FROM Notes`)
if httpError(err, http.StatusInternalServerError, "Failed to load notes", w) { if httpError(err, http.StatusInternalServerError, "Failed to load notes", w) {
@ -72,8 +87,7 @@ func postNotes(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
} }
if len(note.Content) == 0 { if len(note.Content) == 0 {
w.WriteHeader(http.StatusBadRequest) writeError(w, http.StatusBadRequest, "Missing note content")
io.WriteString(w, "Missing note content")
return return
} }
@ -119,8 +133,7 @@ func getNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
err = res.Scan(&note.Content) err = res.Scan(&note.Content)
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound) writeError(w, http.StatusNotFound, "Note doesn't exist")
io.WriteString(w, "Note doesn't exist")
return return
} }
@ -155,8 +168,7 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
} }
if len(note.Content) == 0 { if len(note.Content) == 0 {
w.WriteHeader(http.StatusBadRequest) writeError(w, http.StatusBadRequest, "Missing note content")
io.WriteString(w, "Missing note content")
return return
} }
@ -178,8 +190,7 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
} }
if updated == 0 { if updated == 0 {
w.WriteHeader(http.StatusNotFound) writeError(w, http.StatusNotFound, "Note doesn't exist")
io.WriteString(w, "Note doesn't exist")
return return
} }