diff --git a/pkg/either/errors.go b/pkg/either/errors.go new file mode 100644 index 000000000..f464b8886 --- /dev/null +++ b/pkg/either/errors.go @@ -0,0 +1,35 @@ +package either + +// SyncErr creates an AsyncError either from a synchronous error. +// It wraps the Error into the left field (conventionally associated with the +// error value in the Either pattern) of the Either type. It casts the result +// to the AsyncError type. +func SyncErr(err error) AsyncError { + return AsyncError(Error[chan error](err)) +} + +// AsyncErr creates an AsyncError from an error channel. +// It wraps the error channel into the right field (conventionally associated with +// successful values in the Either pattern) of the Either type. +func AsyncErr(errCh chan error) AsyncError { + return AsyncError(Success[chan error](errCh)) +} + +// SyncOrAsyncError decomposes the AsyncError into its components, returning +// a synchronous error and an error channel. If the AsyncError represents a +// synchronous error, the error channel will be nil and vice versa. +func (soaErr AsyncError) SyncOrAsyncError() (error, chan error) { + errCh, err := Either[chan error](soaErr).ValueOrError() + return err, errCh +} + +// IsSyncError checks if the AsyncError represents a synchronous error. +func (soaErr AsyncError) IsSyncError() bool { + return Either[chan error](soaErr).IsError() +} + +// IsAsyncError checks if the AsyncError represents an asynchronous error +// (sent through a channel). +func (soaErr AsyncError) IsAsyncError() bool { + return Either[chan error](soaErr).IsSuccess() +} diff --git a/pkg/either/types.go b/pkg/either/types.go new file mode 100644 index 000000000..2d08f7945 --- /dev/null +++ b/pkg/either/types.go @@ -0,0 +1,6 @@ +package either + +// AsyncError represents a value which could either be a synchronous error or +// an asynchronous error (sent through a channel). It wraps the more generic +// `Either` type specific for error channels. +type AsyncError Either[chan error]