phasync
Coroutines / AggregateException

Exception

AggregateException

More than one thing failed in one run(): what $fn threw and the failures of coroutines nobody awaited, or several of those.

Introduction#

run() throws this once every coroutine of its frame has ended, when there is more than one failure to report; with exactly one, it throws that exception itself. getExceptions() holds all of them: $fn's first, then the coroutines' failures in the order they happened. None is dropped, and none is picked over the others: with several siblings failing, which one failed first is a matter of timing. The message lists each one with its class, message, file and line, so an uncaught one shows them all; getPrevious() is the first. With an exception handler on the frame (Frame::setExceptionHandler), the handler gets the coroutines' failures one by one instead, and this is not thrown for them.

Class synopsis#

final class AggregateException extends RuntimeException implements \Stringable, \Throwable {
    /* Methods */
    public AggregateException::__construct(array $exceptions)
    public AggregateException::getExceptions(?string $class = null): array
    public AggregateException::contains(string $class): bool
}

Methods#

MethodDescription
__constructWraps $exceptions, which run() does when it has more than one failure to report.
getExceptionsReturns the failures, all of them or those of one class.
containsWhether one of the failures is an instance of $class (subclasses and implementations included).

Examples#

Example 1
try {
    phasync::run(function () {
        phasync::go(function () { phasync::sleep(0.01); throw new RuntimeException('cache down'); });
        phasync::go(function () { phasync::sleep(0.01); throw new LogicException('bad query'); });
    });
} catch (phasync\AggregateException $e) {
    if ($e->contains(LogicException::class)) {
        echo "a bug among ", count($e->getExceptions()), " failures\n";
    }
}

See also#

  • phasync::runRuns $fn and returns its result once it and every coroutine started inside it have ended.
  • Frame::setExceptionHandlerSends the failures of the frame's coroutines that nobody awaited to $handler, one by one, instead of having run() throw them.