Skip to content

Instantly share code, notes, and snippets.

@hollodotme
Created September 13, 2017 18:41
Show Gist options
  • Save hollodotme/d3b5396b7e9e099e6f6dfec74f447af1 to your computer and use it in GitHub Desktop.
Save hollodotme/d3b5396b7e9e099e6f6dfec74f447af1 to your computer and use it in GitHub Desktop.
CompositeException
<?php declare(strict_types=1);


class CompositeException extends \Exception
{
	/** @var array */
	private $throwables = [];

	public function __construct( \Throwable ...$throwables )
	{
		$this->throwables = $throwables;
		parent::__construct((string)$this);
	}

	public function __toString() : string
	{
		$str = '';

		foreach ( $this->throwables as $throwable )
		{
			$str .= "{$throwable->getMessage()}\n\n";
			$str .= "{$throwable->getTraceAsString()}\n\n";
		}

		return $str;
	}
}


$first = new \Exception('First');
$second = new \Exception('Second');
$third = new \Exception('Third');

$previous = new CompositeException($first, $second, $third);

throw new \Exception('Aggregate', 0, $previous);

Prints

PHP Fatal error:  Uncaught CompositeException: First

#0 {main}

Second

#0 {main}

Third

#0 {main}

 in /Users/hollodotme/Sites/holloDotMe/tests/ex.php:36
Stack trace:
#0 {main}

Next Exception: Aggregate in /Users/hollodotme/Sites/holloDotMe/tests/ex.php:38
Stack trace:
#0 {main}
  thrown in /Users/hollodotme/Sites/holloDotMe/tests/ex.php on line 38

Fatal error: Uncaught CompositeException: First

#0 {main}

Second

#0 {main}

Third

#0 {main}

 in /Users/hollodotme/Sites/holloDotMe/tests/ex.php:36
Stack trace:
#0 {main}

Next Exception: Aggregate in /Users/hollodotme/Sites/holloDotMe/tests/ex.php on line 38

Exception: Aggregate in /Users/hollodotme/Sites/holloDotMe/tests/ex.php on line 38

Call Stack:
    0.0002     359032   1. {main}() /Users/hollodotme/Sites/holloDotMe/tests/ex.php:0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment