error_channel.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2019 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 util
  14. import "context"
  15. // ErrorChannel supports non-blocking send and receive operation to capture error.
  16. // A maximum of one error is kept in the channel and the rest of the errors sent
  17. // are ignored, unless the existing error is received and the channel becomes empty
  18. // again.
  19. type ErrorChannel struct {
  20. errCh chan error
  21. }
  22. // SendError sends an error without blocking the sender.
  23. func (e *ErrorChannel) SendError(err error) {
  24. select {
  25. case e.errCh <- err:
  26. default:
  27. }
  28. }
  29. // SendErrorWithCancel sends an error without blocking the sender and calls
  30. // cancel function.
  31. func (e *ErrorChannel) SendErrorWithCancel(err error, cancel context.CancelFunc) {
  32. e.SendError(err)
  33. cancel()
  34. }
  35. // ReceiveError receives an error from channel without blocking on the receiver.
  36. func (e *ErrorChannel) ReceiveError() error {
  37. select {
  38. case err := <-e.errCh:
  39. return err
  40. default:
  41. return nil
  42. }
  43. }
  44. // NewErrorChannel returns a new ErrorChannel.
  45. func NewErrorChannel() *ErrorChannel {
  46. return &ErrorChannel{
  47. errCh: make(chan error, 1),
  48. }
  49. }