github.com/haraldrudell/parl@v0.4.176/err-slice.go (about)

     1  /*
     2  © 2024–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  // ErrSlice is a thread-safe unbound awaitable error container
     9  //   - [ErrSlice.AddError] is a function to submit errors
    10  //   - [ErrSlice.WaitCh] returns a closing channel to await the next error
    11  //   - [ErrSlice.Error] returns the next error value if any
    12  //   - [ErrSlice.Errors] returns a slice of all errors if any
    13  //   - [ErrSlice.EmptyCh] returns a closing channel to await container empty
    14  //     providing deferred-close functionality
    15  //   - ErrSlice features:
    16  //   - — real-time error stream or
    17  //   - — collect errors at end and
    18  //   - — close then read-to-end function
    19  //   - implements [parl.Errs] [parl.ErrorSink]
    20  type ErrSlice struct {
    21  	// errs is a thread-safe, unbound awaitable slice of errors
    22  	errs AwaitableSlice[error]
    23  }
    24  
    25  // ErrSlice provides error one-at-a-time or all-at-once
    26  var _ Errs = &ErrSlice{}
    27  
    28  // ErrSlice has AddError error sink method
    29  var _ ErrorSink = &ErrSlice{}
    30  
    31  // Error returns the next error value
    32  //   - hasValue true: err is valid
    33  //   - hasValue false: the error source is empty
    34  func (e *ErrSlice) Error() (error, bool) { return e.errs.Get() }
    35  
    36  // Errors returns a slice of errors or nil
    37  func (e *ErrSlice) Errors() (errs []error) { return e.errs.GetAll() }
    38  
    39  // WaitCh waits for the next error, possibly indefinitely
    40  //   - a received channel closes on errors available
    41  //   - the next invocation may return a different channel object
    42  func (e *ErrSlice) WaitCh() (ch AwaitableCh) { return e.errs.DataWaitCh() }
    43  
    44  // AddError is a function to submit non-fatal errors
    45  func (e *ErrSlice) AddError(err error) { e.errs.Send(err) }
    46  
    47  // EmptyCh returns an awaitable channel that closes on queue being or
    48  // becoming empty
    49  //   - doNotInitialize CloseAwaiter: obtain the channel but do not enable it closing.
    50  //     A subsequent invocation with doNotInitialize missing will enable its closing thus
    51  //     act as a deferred Close function
    52  func (e *ErrSlice) EmptyCh(doNotInitialize ...bool) (ch AwaitableCh) {
    53  	return e.errs.EmptyCh(doNotInitialize...)
    54  }