编码/ csv:我应该将Error()与WriteAll()一起使用吗?

In the golang docs for encoding/csv, WriteAll is stated to Write the given CSV records, and then to call Flush on the underlying writer.

Now, I'm confused as to whether I should detect errors during WriteAll via its return value, or the Error() method. Let me explain why.

  • Write returns error. This makes me think I can detect errors based on its return value.
  • Flush doesn't return error, and the docs explicitly say "To check if an error occurred during the Flush, call Error."
  • WriteAll mentions nothing about error handling, but it returns error, and states it performs both Write and Flush. The docs include an example that goes like this:

    w := csv.NewWriter(os.Stdout)
    w.WriteAll(records) // calls Flush internally
    
    if err := w.Error(); err != nil {
        log.Fatalln("error writing csv:", err)
    }
    
  • Error() itself states: "Error reports any error that has occurred during a previous Write or Flush." (emphasis mine).

I looked at the code and I saw some shenanigans I wasn't familiar with, so I'm turning the question to SO.

Which is it, then? Should I look at the returned error? Should I use w.Error()? Should I use both? What's the difference?

As far as i can see you can use both, i would propose to use the error from

err := w.WriteAll(records)

this is more common in go.

All errors returned are coming from the *bufio.Writer, and if it fails it will always return an error. So if w.WriteAll returns an error a call to Error() will also return an error.