error_tracker.go 730 B

12345678910111213141516171819202122232425262728293031323334
  1. package generator
  2. import (
  3. "io"
  4. )
  5. // ErrorTracker tracks errors to the underlying writer, so that you can ignore
  6. // them until you're ready to return.
  7. type ErrorTracker struct {
  8. io.Writer
  9. err error
  10. }
  11. // NewErrorTracker makes a new error tracker; note that it implements io.Writer.
  12. func NewErrorTracker(w io.Writer) *ErrorTracker {
  13. return &ErrorTracker{Writer: w}
  14. }
  15. // Write intercepts calls to Write.
  16. func (et *ErrorTracker) Write(p []byte) (n int, err error) {
  17. if et.err != nil {
  18. return 0, et.err
  19. }
  20. n, err = et.Writer.Write(p)
  21. if err != nil {
  22. et.err = err
  23. }
  24. return n, err
  25. }
  26. // Error returns nil if no error has occurred, otherwise it returns the error.
  27. func (et *ErrorTracker) Error() error {
  28. return et.err
  29. }