logoalt Hacker News

Pxtllast Tuesday at 7:09 PM1 replyview on HN

I've never used Go but having used other languages with exception-based error handling, I get why Go decided to go in a different direction... but reading this over...

Okay, so surely some syntactic sugar could make it more pleasant than the

  if (err != nil) {
    return nil, err
  }
repeated boilerplate. Like, if that return is a tagged union you could do some kind of pattern matching?

... oh, Go doesn't have sum-types. Or pattern matching.

Could you at least do some kind of generic error handler so I can call

  y := Handle(MyFuncThatCanReturnError(x))
?

... Okay, GoLang does not have tuples. Multiple returns must be handled separately.

Okay could I write some kind of higher-order function that handles it in a generic way? Like

  y := InvokeWithErrorHandler(MyFuncThatCanReturnError, x)
?

No? That's not an option either?

... why do you all do this to yourselves?


Replies

tail_exchangelast Tuesday at 7:54 PM

This doesn't actually makes the process simpler.

Error handling in Go is not just writing "if err != nil { return nil, err }" for every line. You are supposed to enrich the error to add more context to it. For example:

    result, err := addTwoNumbers(a, b)
    if err != nil {
      return fmt.Errorf("addTwoNumbers(%d, %d) = %v", a, b, err)
    }
This way you can enrich the error message and say what was passed to the function. If you try to abstract this logic with a "Handle" function, you'll just create a mess. You'll save yourself the time of writing an IF statement, but you'll need a bunch of arguments that will just make it harder to use.

Not to mention, those helper functions don't account for cases where you don't just want to bubble up an error. What if you want to do more things, like log, emit metrics, clean up resources, and so on? How do you deal with that with the "Handle()" function?

show 1 reply