From 2124f2f882f4c36f40e67447ed4ede75cceb6ac7 Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Tue, 21 Oct 2025 19:02:42 +0200 Subject: [PATCH] Using the new error's helper methods inside our current API endpoint and with our httprouter Handlers NotFound and MethodNotAllowed (will override the default responses with our helper's methods) --- cmd/api/healthcheck.go | 4 ++-- cmd/api/movies.go | 7 ++++--- cmd/api/routes.go | 6 ++++++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/cmd/api/healthcheck.go b/cmd/api/healthcheck.go index 2c6d2a4..2314c1b 100644 --- a/cmd/api/healthcheck.go +++ b/cmd/api/healthcheck.go @@ -21,7 +21,7 @@ func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Reques err := app.writeJSON(w, http.StatusOK, env, nil) if err != nil { - app.logger.Error(err.Error()) - http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError) + // Use the new serverErrorResponse() helper + app.serverErrorResponse(w, r, err) } } diff --git a/cmd/api/movies.go b/cmd/api/movies.go index d197d05..c9a33ab 100644 --- a/cmd/api/movies.go +++ b/cmd/api/movies.go @@ -17,7 +17,8 @@ func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) id, err := app.readIDParam(r) if err != nil || id < 1 { - http.NotFound(w, r) + // Use the new notFoundResponse() helper + app.notFoundResponse(w, r) return } @@ -38,7 +39,7 @@ func (app *application) showMovieHandler(w http.ResponseWriter, r *http.Request) // Encode the struct to JSON and send it as the HTTP response. err = app.writeJSON(w, http.StatusOK, envelope{"movie": movie}, nil) if err != nil { - app.logger.Error(err.Error()) - http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError) + // Use the new serverErrorResponse() helper + app.serverErrorResponse(w, r, err) } } diff --git a/cmd/api/routes.go b/cmd/api/routes.go index 2750931..57904bc 100644 --- a/cmd/api/routes.go +++ b/cmd/api/routes.go @@ -9,6 +9,12 @@ func (app *application) routes() http.Handler { // Initialize a new httprouter router instance router := httprouter.New() + // Convert the notFoundResponse() helper to a http.Handler using the http.HandlerFunc() adapter, and then set it as the custom error handler for 404 Not Found responses. + router.NotFound = http.HandlerFunc(app.notFoundResponse) + + // Likewise, convert the methodNotAllowedResponse() helper to a http.Handler and set it as the custom error handler for 405 Method Not Allowed responses + router.MethodNotAllowed = http.HandlerFunc(app.methodNotAllowedResponse) + /* Register the relevant methods, URL patterns and handler functions for our endpoints using the HandlerFunc() method. Note that http.MethodGet and