I have recently gotten into Go and have seen a lot of discussion about how to do error handling.
the pattern that I have seen laid out is the following:
err := DoSomething() if err != nil { //handle } // continue often times when managing amqp connections, my condition is that I want to continue only if the error is nil, because then I need to do something on the connection:
c, err := Connect() if err != nil { return nil, err } s,err := c.RegisterSomethingOnConnection() if err != nil { return nil, err } val, err := s.DoSomething() return val, err as you can see I only want to run the line c.RegisterSomethingOnConnection if the error returned from Connect() is nil.
However, I dislike the above due to the early returns. Early returns make me uncomfortable because in the long run it hurts readability and obscures exactly when a function exits. My solution so far has been to do the following:
var err error var val ReturnType c,err := Connect() if err == nil { s,err := c.RegisterSomethingOnConnection() if err == nil { val,err = s.DoSomething() } } return val,err I like to do this for 2 reasons. First, it prevents returning nil. Second, I find it makes the code more maintainable as you can add easily add functionality before returning (i.e. logging) and not have certain paths miss the added functionality due to an early return.
Is what I have done acceptable idiomatic Go or do I just need to get over my dislike of early returns and follow the that pattern?