2 ms·
You just generated a 502, and spent a bunch of extra lines doing it. The 502 is bad, and if that's all I need to do, I get that almost for free from net/http's
by tptacek 5y ago
You just generated a 502, and spent a bunch of extra lines doing it. The 502 is bad, and if that's all I need to do, I get that almost for free from net/http's panic handler. It sounds like you don't actually have a problem here.
- claudiawerner 5y agoI think that was more of an example. There are lots of ways to fail gracefully when you don't have the data you want in the dict.
- tptacek 5y agoRight, which is why json.Unmarshal returns an error, and why map lookups return an extra `ok` value in Go.
- tgsovlerkhgsel 5y agoIt would be a lot more than 4 lines in Go though. Either the struct definition, or a lot of `if !ok return error`. Especially once the nesting gets deeper.
- tptacek 5y agoI'm pretty sure it would just be an `if err != nil {http.Error(w, err.Error(), 501); return }`.
- tgsovlerkhgsel 5y agoone of these for each nesting level.
- tgsovlerkhgsel 5y agoI kept the example simple, of course I could now customize the error message further (or take some other sensible action). Note that I returned a 400, not a generic 502 here. If I didn't care at all, I wouldn't need any extra lines. Does the panic handler send a response at all, or does it just drop the connection? Also, in Go, using panic/recover is considered unidiomatic. You can use it like an exception system, but it's not what you're supposed to do.
- tptacek 5y agoI'm not suggesting that you would build a custom exception recovery system; I'm pointing out that net/http, which is definitionally idiomatic, already has that recovery mechanism.
- tgsovlerkhgsel 5y agoI believe that that recovery mechanism isn't supposed to be routinely triggered just due to bad user input, and that code that does so would be considered defective.
- tptacek 5y agoIt's doing almost literally the same thing as the Python code upthread. Just, with less code.