-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathCompositeException.php
62 lines (49 loc) · 1.47 KB
/
CompositeException.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace Psl\Async\Exception;
use Exception;
use Psl\Str;
use Throwable;
use function count;
use const PHP_EOL;
final class CompositeException extends Exception implements ExceptionInterface
{
/**
* @var non-empty-array<array-key, Throwable>
*/
private array $reasons;
/**
* @param non-empty-array<array-key, Throwable> $reasons Array of exceptions.
* @param string|null $message Exception message, defaults to message generated from passed exceptions.
*/
public function __construct(array $reasons, null|string $message = null)
{
parent::__construct($message ?? $this->generateMessage($reasons));
$this->reasons = $reasons;
}
/**
* @return non-empty-array<array-key, Throwable>
*/
public function getReasons(): array
{
return $this->reasons;
}
/**
* @param non-empty-array<array-key, Throwable> $reasons
*/
private function generateMessage(array $reasons): string
{
$message = Str\format(
'"Multiple errors encountered (%d); use "%s::getReasons()" to retrieve the array of exceptions thrown:',
count($reasons),
self::class,
);
foreach ($reasons as $reason) {
$message .= PHP_EOL . PHP_EOL . $reason::class;
if ($reason->getMessage() !== '') {
$message .= ': ' . $reason->getMessage();
}
}
return $message;
}
}