Skip to content

Instantly share code, notes, and snippets.

@andreyserdjuk
Created January 17, 2022 13:21
Show Gist options
  • Save andreyserdjuk/9e52c94dfb3e2cd08c9602f077b5ec7d to your computer and use it in GitHub Desktop.
Save andreyserdjuk/9e52c94dfb3e2cd08c9602f077b5ec7d to your computer and use it in GitHub Desktop.
flatten parent exceptions
<?php
function a() {
throw new \LogicException('bad logic in A');
}
function b() {
try {
a();
} catch (\LogicException $e) {
throw new \RuntimeException('Runtime exception from B: ' . $e->getMessage(), 0, $e);
}
}
function c() {
b();
}
try {
c();
} catch (\RuntimeException $e) {
$messages = [];
$exception = $e;
do {
$messages[] = sprintf(
"%s was thrown with message: \"%s\"\r\n%s",
get_class($exception),
$exception->getMessage(),
$exception->getTraceAsString()
);
$exception = $exception->getPrevious();
} while ($exception !== null);
echo implode("\r\n==========\r\n", $messages);
}
@andreyserdjuk
Copy link
Author

andreyserdjuk commented Jan 17, 2022

Will render:

RuntimeException was thrown with message: "Runtime exception from B: bad logic in A"
#0 /var/www/current/test.php(16): b()
#1 /var/www/current/test.php(20): c()
#2 {main}
==========
LogicException was thrown with message: "bad logic in A"
#0 /var/www/current/test.php(9): a()
#1 /var/www/current/test.php(16): b()
#2 /var/www/current/test.php(20): c()

The same approach \Symfony\Component\ErrorHandler\Exception\FlattenException::getAllPrevious()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment