Skip to content

Commit

Permalink
encoding/csv: add Error method to Writer
Browse files Browse the repository at this point in the history
Fixed issue 3931

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/6923049
  • Loading branch information
ryanslade authored and rsc committed Dec 11, 2012
1 parent c694457 commit 9a12a9c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/pkg/encoding/csv/writer.go
Expand Up @@ -92,10 +92,17 @@ func (w *Writer) Write(record []string) (err error) {
}

// Flush writes any buffered data to the underlying io.Writer.
// To check if an error occured during the Flush, call Error.
func (w *Writer) Flush() {
w.w.Flush()
}

// Error reports any error that has occurred during a previous Write or Flush.
func (w *Writer) Error() error {
_, err := w.w.Write(nil)
return err
}

// WriteAll writes multiple CSV records to w using Write and then calls Flush.
func (w *Writer) WriteAll(records [][]string) (err error) {
for _, record := range records {
Expand Down
28 changes: 28 additions & 0 deletions src/pkg/encoding/csv/writer_test.go
Expand Up @@ -6,6 +6,7 @@ package csv

import (
"bytes"
"errors"
"testing"
)

Expand Down Expand Up @@ -42,3 +43,30 @@ func TestWrite(t *testing.T) {
}
}
}

type errorWriter struct{}

func (e errorWriter) Write(b []byte) (int, error) {
return 0, errors.New("Test")
}

func TestError(t *testing.T) {
b := &bytes.Buffer{}
f := NewWriter(b)
f.Write([]string{"abc"})
f.Flush()
err := f.Error()

if err != nil {
t.Errorf("Unexpected error: %s\n", err)
}

f = NewWriter(errorWriter{})
f.Write([]string{"abc"})
f.Flush()
err = f.Error()

if err == nil {
t.Error("Error should not be nil")
}
}

0 comments on commit 9a12a9c

Please sign in to comment.