4 ms·
You are right that go lets you shoot yourself in the foot pretty hard. Hopefully all the underscores in foo, _ := bar() makes your code reviewer think "nope".
by jrockway 8y ago
You are right that go lets you shoot yourself in the foot pretty hard. Hopefully all the underscores in foo, _ := bar() makes your code reviewer think "nope". But I don't think it's better or worse than the alternative, just different. I don't find if err != nil { return err } to be that onerous, because I like consciously making the decision "this function call can fail and this is exactly what I want to happen". I feel like in the end you get the same effect as exceptions, without having an additional concept in your programming language. Tests are easy to write, make something fail and then check what err is equal to. No magic required.
I think recover() is basically almost always wrong, except around libraries that are written incorrectly and panic instead of returning errors for recoverable faults. (panic("your password is incorrect")). Writing to a closed channel or indexing off the end of an array is not a runtime error, but an error in the design of the program. I am not sure what you are saving by keeping the program alive.
So for your example, I think you are basically correct that that's what things should look like. Kill the defer/recover and let the context control the timeout. If you want to try things 3 times and have it either succeed or timeout, I don't see what choice you have but to have a for loop with 3 iterations and something that waits for the result or the timeout.
Perhaps what people want is a library that handles all failures correctly so that they don't see the possible ways things can go wrong. That's a worthy goal and I encourage people to try. In the original article, it sounded like that's what the author wanted, and his solution was to return errors out of band and have "something else" "handle them" "later". Let me know how that works out for you. If only it were that easy!