Handling multiple errors in go

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

    In a situation like this, I usually just flatten it out a bit.

    func myFunc() (err error) {
        cmd := exec.Command("cat", "-")
    
        stdin,  err := cmd.StdinPipe();                  if err != nil { return }
        stdout, err := cmd.StdoutPipe();                 if err != nil { return }
    
           err  = cmd.Start();                           if err != nil { return }
        _, err  = io.WriteString(stdin, "Hello world!"); if err != nil { return }
           err  = stdin.Close();                         if err != nil { return }
        o, err := ioutil.ReadAll(stdout);                if err != nil { return }
    
        fmt.Println(string(o))
        return
    }
    

    Still ugly, but at least it's less vertical, and we get some alignment.

    I can't say this adheres to any sort of convention, but it's a whole lot easier to read IMO.

提交回复
热议问题