Menu

Reference / Async

AggregateError

finalclass
final class AggregateError extends \RuntimeException

Several task errors as one throwable.

Thrown by awaitAny() when every input task failed. getPrevious() is the first error, as a representative cause; errors() is the full map keyed by the failing task's input position.

Example

use Async\AggregateError;
use function Async\async;
use function Async\awaitAny;
use function Async\delay;
use function Async\spawn;

async(function () {
    // A failure is ignored while another task can still succeed.
    $fails = spawn(function () { delay(0.01); throw new RuntimeException("mirror 1 down"); });
    $wins = spawn(function () { delay(0.02); return "mirror 2"; });
    echo awaitAny($fails, $wins), "\n";

    // Only when every task failed does awaitAny() throw.
    $x = spawn(function () { throw new RuntimeException("first"); });
    $y = spawn(function () { delay(0.01); throw new RuntimeException("second"); });
    try {
        awaitAny($x, $y);
    } catch (AggregateError $e) {
        foreach ($e->errors() as $i => $err) {
            echo "task $i: ", $err->getMessage(), "\n";
        }
    }
});

Output

mirror 2
task 0: first
task 1: second

See also: awaitAny

Methods

__construct()Build an aggregate from a message and the individual errors.
errors()Every collected error, keyed by the failing task's input position.

__construct()#source

function __construct(string $message, private array $errors)

Build an aggregate from a message and the individual errors.

Parameters

$message string
the exception message
$errors array<int, \Throwable>
keyed by input position

errors()#source

function errors(): array

Every collected error, keyed by the failing task's input position.

Returns

array<int, \Throwable> — the errors, keyed by input position

View source