go - Golang idomatic nested error handling -


i have gotten go , have seen lot of discussion how error handling.

the pattern have seen laid out following:

err := dosomething() if err != nil {    //handle } // continue 

often times when managing amqp connections, condition want continue if error nil, because need on 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 can see want run line c.registersomethingonconnection if error returned connect() nil.

however, dislike above due returns. returns make me uncomfortable because in long run hurts readability , obscures when function exits. solution far has been 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 2 reasons. first, prevents returning nil. second, find makes code more maintainable can add add functionality before returning (i.e. logging) , not have paths miss added functionality due return.

is have done acceptable idiomatic go or need on dislike of returns , follow pattern?

one of go prover is:

don’t check errors, handle them gracefully

i recommend read post dave cheney

i put highlights here:

"there no single way handle errors. instead, believe go’s error handling can classified 3 core strategies"

  • sentinel errors:

if err == errsomething { … }

"using sentinel values least flexible error handling strategy, caller must compare result predeclared value using equality operator. presents problem when want provide more context, returning different error break equality check."

  • error types

if err, ok := err.(sometype); ok { … }

"an error type type create implements error interface. "

  • opaque errors

x, err := bar.foo() if err != nil { return err } // use x

"i call style opaque error handling, because while know error occurred, don’t have ability see inside error. caller, know result of operation worked, or didn’t."

.... read post.

i think important aspect of error handling don’t check errors, handle them gracefully, hope can you.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -