From f407cf8909a750ccf7c1f696e525408d0c69e93d Mon Sep 17 00:00:00 2001 From: ergz Date: Wed, 21 Jun 2023 22:12:48 -0700 Subject: [PATCH] adds custom response errors --- cmd/api/errors.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 cmd/api/errors.go diff --git a/cmd/api/errors.go b/cmd/api/errors.go new file mode 100644 index 0000000..b42f1b0 --- /dev/null +++ b/cmd/api/errors.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "net/http" +) + +func (app *application) logError(r *http.Request, err error) { + app.logger.Print(err) +} + +func (app *application) errorResponse(w http.ResponseWriter, r *http.Request, status int, message any) { + env := envelope{"error": message} + + err := app.writeJSON(w, status, env, nil) + if err != nil { + app.logError(r, err) + w.WriteHeader(500) + } +} + +func (app *application) serverErrorResponse(w http.ResponseWriter, r *http.Request, err error) { + app.logError(r, err) + + message := "the server encountered an error and could not process your request" + app.errorResponse(w, r, http.StatusInternalServerError, message) +} + +func (app *application) notFoundResponse(w http.ResponseWriter, r *http.Request) { + message := "the requested resources could not be found" + app.errorResponse(w, r, http.StatusNotFound, message) +} + +func (app *application) methodNotAllowedResponse(w http.ResponseWriter, r *http.Request) { + message := fmt.Sprintf("the %s method is not supported for this resource", r.Method) + app.errorResponse(w, r, http.StatusMethodNotAllowed, message) +}