From c3fdb40ae41fb3994af3910548467b8c1807a5b1 Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Sat, 25 Oct 2025 09:57:41 +0200 Subject: [PATCH] Adding more context for invalidUnmarshalError management inside readJSON function. Updating 'Panicking vs returning errors' section. --- README.md | 4 ++++ cmd/api/helpers.go | 1 + 2 files changed, 5 insertions(+) diff --git a/README.md b/README.md index 36d2b7c..7283295 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,10 @@ The other class of errors are _unexpected errors_.These are errors which should I'd recommend trying to return and gracefully handle unexpected errors in most cases. The exception to this is when _returning the error_ adds an unacceptable amount of error handling to the rest of your codebase. +'Go By example' page on panics summarizes all of this quite nicely: + +_A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn't occur during normal operation and that we aren't prepared to handle gracefully._ + ### Performance **json.MarshalIndent()** takes 65% longer to run and uses around 30% more memory than **json.Marshal()**, as well as making two more heap allocations. Those figures will change depending on what you're encoding, but they're fairly indicative of the performance impact. diff --git a/cmd/api/helpers.go b/cmd/api/helpers.go index 9caf819..bcd1be6 100644 --- a/cmd/api/helpers.go +++ b/cmd/api/helpers.go @@ -115,6 +115,7 @@ func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any return errors.New("body must not be empty") // A json.InvalidUnmarshalError error will be returned if we pass something that is not a non-nil pointer to Decode(). We catch this and panic, rather than returning an error to our handler. + // This is firmly an unexpected error which we shouldn't see under normal operation, and is something that should be picked up in development and tests long before deployment. case errors.As(err, &invalidUnmarshalError): panic(err)