error_tracker.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package generator
  14. import (
  15. "io"
  16. )
  17. // ErrorTracker tracks errors to the underlying writer, so that you can ignore
  18. // them until you're ready to return.
  19. type ErrorTracker struct {
  20. io.Writer
  21. err error
  22. }
  23. // NewErrorTracker makes a new error tracker; note that it implements io.Writer.
  24. func NewErrorTracker(w io.Writer) *ErrorTracker {
  25. return &ErrorTracker{Writer: w}
  26. }
  27. // Write intercepts calls to Write.
  28. func (et *ErrorTracker) Write(p []byte) (n int, err error) {
  29. if et.err != nil {
  30. return 0, et.err
  31. }
  32. n, err = et.Writer.Write(p)
  33. if err != nil {
  34. et.err = err
  35. }
  36. return n, err
  37. }
  38. // Error returns nil if no error has occurred, otherwise it returns the error.
  39. func (et *ErrorTracker) Error() error {
  40. return et.err
  41. }