top | item 44173990

(no title)

tail_exchange | 9 months ago

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?

discuss

order

Pxtl|9 months ago

Obviously I'm being terse for argument.

You can easily imagine

  InvokeWithErrorLogger(fn, fnparam, log)
or

  InvokeWithErrorAnnotator(fn, fnparam, annotatorFn)
Or any other common error-handling pattern.

tail_exchange|9 months ago

Perhaps something like this?

    result := InvokeWithErrorLogger(
        func (err error) { // Error handler
            incrementMetric("foo")
            log.Error("bar")
        },
        addTwoNumbers, a, b,
    )

But the problem is that this approach is not better than just writing this, which doesn't need any new fancy addition to the language:

    result, err := addTwoNumbers(a, b)
    if err != nil {
        incrementMetric("foo")
        log.Error("bar")
        return fmt.Errorf("addTwoNumbers(%d, %d) = %v", a, b, err)
    }
Hence why all the proposals ended up dying with the lack of traction.