hashicorp / hashicorp/go-multierror

Add context-aware cancellation support (similar to errgroup.WithContext) for multierror.Group

Open
#127 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
2.6k
Forks
143
PR merge metrics
No merged PRs in 30d

Description

## Summary
Currently, `multierror.Group` does not provide any mechanism to cancel or short-circuit goroutines when a context is canceled or when one of the goroutines fails. This makes it difficult to implement workflows where early termination is desired.

## Motivation
The `golang.org/x/sync/errgroup` package supports `WithContext`, which allows goroutines to be canceled if the context is done or if an error occurs. However, `errgroup` only returns the first error, while `multierror.Group` is designed to aggregate all errors. It would be extremely useful to combine these two behaviors:
- Context propagation and cancellation (like `errgroup.WithContext`)
- Error aggregation (like `multierror.Group`)

## Proposal
Add a `WithContext` variant (e.g. `multierror.WithContext(ctx)` returning a `Group`) or extend `Group` itself with context handling support. This would allow:
- Cancelling remaining goroutines when the context is canceled
- Still collecting and returning all errors that occurred up until cancellation

## Use cases
- Long-running operations where only the first error should trigger cancellation, but all errors encountered before cancellation should still be reported
- Workflows that need to respect deadlines/timeouts while aggregating multiple errors
- More ergonomic parity with `errgroup` while maintaining the strengths of `multierror`

## Alternatives
- Manually handling cancellation logic outside of `multierror.Group`
- Wrapping `errgroup.WithContext` and manually aggregating errors, which results in duplicated boilerplate code

## Additional context
This would bring feature parity with `errgroup`, while offering error aggregation, making `multierror.Group` much more practical for concurrent workloads.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.