3 ms·
I dislike the example. The author says that because we have a complex function, and the HTTP handler is designed the way it is, we cannot avoid running into pr
by vrnvu 4y ago
I dislike the example.
The author says that because we have a complex function, and the HTTP handler is designed the way it is, we cannot avoid running into problems. I disagree. This are two separate things.
You could take a more functional approach and separate the main logic and the side effect. Which is writing the response.
func aMoreAdvancedHandler(w http.ResponseWriter, r *http.Request) {
res, err := helper()
if err {
http.Error(w, err.Error(), err.Status())
}
w.write(res)
}
func helper() ([]byte, err error) {
// todo
}
Where now the helper function has the problem of dealing with multiple operations that can potentially fail. Which is exactly the problem in the example. Not the HTTP handler itself...
For example, we could use the defer function call with a named error to check if something fails and guarantee that we always return an appropriate error. Similar to the pattern used to free resources... I don't know how is this commonly called. But again, the problem is the helper function not the handler.
I don't want to use the FP terminology, probably most people are familiar with this pseudo-code:
func helper() (res, err) {
return foo().bar().baz()
}
Where the chain foo, bar, baz will continue to be executed if all the calls are success, but early terminate if an error occurs.
So, where is the problem?
- FpUser 4y agoI very much prefer this approach as well. Way better than endless chaining of this().that().repeat().million().times().
- kissgyorgy 4y agoIt's very funny that you trying to invalidate the problem OP is explaining and you made the exact same mistake in 10 lines of code :) You forgot to return from the error handling branch.