Handling multiple errors in go

前端 未结 4 1301
生来不讨喜
生来不讨喜 2020-12-17 19:17

I\'m new to go and finding the error handling to be extremely verbose. I\'ve read the reasoning for it and mostly agree, but there are a few places where it seems like ther

4条回答
  •  生来不讨喜
    2020-12-17 19:54

    Clearly, we must handle any errors; we can't just ignore them.

    For example, trying to make the example less artificial,

    package main
    
    import (
        "fmt"
        "io"
        "io/ioutil"
        "os"
        "os/exec"
    )
    
    func piping(input string) (string, error) {
        cmd := exec.Command("cat", "-")
        stdin, err := cmd.StdinPipe()
        if err != nil {
            return "", err
        }
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            return "", err
        }
        err = cmd.Start()
        if err != nil {
            return "", err
        }
        _, err = io.WriteString(stdin, input)
        if err != nil {
            return "", err
        }
        err = stdin.Close()
        if err != nil {
            return "", err
        }
        all, err := ioutil.ReadAll(stdout)
        output := string(all)
        if err != nil {
            return output, err
        }
        return output, nil
    }
    
    func main() {
        in := "Hello world!"
        fmt.Println(in)
        out, err := piping(in)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        fmt.Println(out)
    }
    

    Output:

    Hello world!
    Hello world!
    

    Error Handling and Go

    In Go, error handling is important. The language's design and conventions encourage you to explicitly check for errors where they occur (as distinct from the convention in other languages of throwing exceptions and sometimes catching them). In some cases this makes Go code verbose.

提交回复
热议问题