DEV Community

Discussion on: Go 2 Draft: Error Handling

Collapse
 
theodesp profile image
Theofanis Despoudis • Edited

Eventually you do something like this:

package main

import (
    "log"
    "io/ioutil"
    "os"
)

func main() {
    handle := func (v interface{}, err error) interface{} {
        if err != nil {
            log.Fatal(err)
        }
        return v
    }

    hex := handle(ioutil.ReadAll(os.Stdin))
    data := handle(parseHexdump(string(hex)))
    os.Stdout.Write(data)
}

Which I've seen in some other examples as:

package main

import (
    "log"
    "io/ioutil"
    "os"
)

func main() {
    checkError := func (err error) {
        if err != nil {
            log.Fatal(err)
        }
    }

    hex, err := ioutil.ReadAll(os.Stdin)
    checkError(err)
    data, err = parseHexdump(string(hex))
    checkError(err)
    os.Stdout.Write(data)
}

To be honest, while this proposed solution works, it still looks like we only saving a few keystrokes. It's good but not great.

Collapse
 
dean profile image
dean

That doesn't work for returning errors, though. What if I wanted to return a wrapped version of the error?

Collapse
 
theodesp profile image
Theofanis Despoudis • Edited

Fair enough, but in that case, the wrapping is implicit and it looks like a twisted version of a try/catch block, something that spreads confusion.

I would prefer something like this:

func main() {
    check {
        hex := ioutil.ReadAll(os.Stdin)
        data := parseHexdump(string(hex))
        os.Stdout.Write(data)
    } handle err {
        switch err.(type) {
    case *os.ErrNotExist:
        // Code...
    case ...:
        // ...
    default:
        // ...
    }
}

As its more structured, easier to read and less confusing than the draft proposal. Note that the handle could be triggered multiple times just as the original handle version.

Thread Thread
 
dean profile image
dean

But now there's very implicit error checking, you don't know which lines may result in an error, which is something the proposal was trying to avoid.

Collapse
 
alsotang profile image
alsotang

It's totally different. By your way, you can stop the subsequent operations when an error occurs