Better error responses
This commit is contained in:
parent
84b877017c
commit
13a199afee
31
main.go
31
main.go
@ -22,14 +22,29 @@ type Note struct {
|
||||
func httpError(err error, statusCode int, message string, w http.ResponseWriter) bool {
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
w.WriteHeader(statusCode)
|
||||
io.WriteString(w, message)
|
||||
writeError(w, statusCode, message)
|
||||
return true
|
||||
}
|
||||
|
||||
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) {
|
||||
res, err := db.Query(`SELECT Id, Content FROM Notes`)
|
||||
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 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, "Missing note content")
|
||||
writeError(w, http.StatusBadRequest, "Missing note content")
|
||||
return
|
||||
}
|
||||
|
||||
@ -119,8 +133,7 @@ func getNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
|
||||
|
||||
err = res.Scan(¬e.Content)
|
||||
if err == sql.ErrNoRows {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
io.WriteString(w, "Note doesn't exist")
|
||||
writeError(w, http.StatusNotFound, "Note doesn't exist")
|
||||
return
|
||||
}
|
||||
|
||||
@ -155,8 +168,7 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
|
||||
}
|
||||
|
||||
if len(note.Content) == 0 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, "Missing note content")
|
||||
writeError(w, http.StatusBadRequest, "Missing note content")
|
||||
return
|
||||
}
|
||||
|
||||
@ -178,8 +190,7 @@ func putNote(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
|
||||
}
|
||||
|
||||
if updated == 0 {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
io.WriteString(w, "Note doesn't exist")
|
||||
writeError(w, http.StatusNotFound, "Note doesn't exist")
|
||||
return
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user