Handling multiple errors in go

前端 未结 4 1291
生来不讨喜
生来不讨喜 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:31

    I just wrote a few hundreds lines in Go, so I'm not titled to indicate any idiomatic way. However, in case of repetitive call-and-check-error steps , I find that the code is a bit easier to write and to read as well if I revert the logic : instead of checking the condition for exiting (err != nil ), I check the condition for continuing ( err == nil ), like shown below.
    This can be done, if you have an unique way to handle the error, no matter which error is, like returning to the caller or printing/logging it. The drawback to this approach is that you can't implicitly declare the variables with :=, because they would have the scope of the if block in which they are assigned.

    func main() {
        var output []byte
        var stdin io.WriteCloser 
        var stdout io.Reader 
    
        cmd := exec.Command("cat", "-")
    
        stdin, err := cmd.StdinPipe()
    
        if err == nil {
          stdout, err = cmd.StdoutPipe()
        }
    
        if err == nil {
          err = cmd.Start()
        }
    
        if err == nil {
          _, err = io.WriteString(stdin, "Hello world!")
        }
    
        if err == nil {
        output, err = ioutil.ReadAll(stdout)
        } 
    
        if err == nil {
         err = stdin.Close();
        }
    
        if err == nil {
                fmt.Println(string(output))
        } else {
             fmt.Println(string(err.Error())) // Error handling goes here
        }
    
        return
    }
    

提交回复
热议问题