Adding more context for invalidUnmarshalError management inside readJSON function. Updating 'Panicking vs returning errors' section.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 54s
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 54s
This commit is contained in:
@@ -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.
|
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
|
### 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.
|
**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.
|
||||||
|
|||||||
@@ -115,6 +115,7 @@ func (app *application) readJSON(w http.ResponseWriter, r *http.Request, dst any
|
|||||||
return errors.New("body must not be empty")
|
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.
|
// 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):
|
case errors.As(err, &invalidUnmarshalError):
|
||||||
panic(err)
|
panic(err)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user