From 8d8da79932a768b1e87a37b1a1c86ffb48806bd6 Mon Sep 17 00:00:00 2001 From: Christoph Wurst Date: Mon, 30 Nov 2020 20:40:45 +0100 Subject: [PATCH] Fix normalizing an exception that wraps a throwable Signed-off-by: Christoph Wurst --- src/Normalizer.php | 8 +++++--- tests/NormalizerTest.php | 31 +++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/Normalizer.php b/src/Normalizer.php index 9f6381f..2452996 100644 --- a/src/Normalizer.php +++ b/src/Normalizer.php @@ -14,6 +14,8 @@ namespace InterfaSys\LogNormalizer; +use Throwable; + /** * Converts any variable to a String * @@ -252,7 +254,7 @@ private function normalizeDate($data) { */ private function normalizeObject($data, $depth) { if (is_object($data)) { - if ($data instanceof \Exception) { + if ($data instanceof Throwable) { return $this->normalizeException($data); } // We don't need to go too deep in the recursion @@ -275,11 +277,11 @@ private function normalizeObject($data, $depth) { /** * Converts an Exception to String * - * @param \Exception $exception + * @param Throwable $exception * * @return string[] */ - private function normalizeException(\Exception $exception) { + private function normalizeException(Throwable $exception) { $data = [ 'class' => get_class($exception), 'message' => $exception->getMessage(), diff --git a/tests/NormalizerTest.php b/tests/NormalizerTest.php index bb163cd..3ef75fb 100644 --- a/tests/NormalizerTest.php +++ b/tests/NormalizerTest.php @@ -15,7 +15,9 @@ namespace InterfaSys\LogNormalizer; +use Exception; use PHPUnit\Framework\TestCase; +use TypeError; use function get_class; /** @@ -309,6 +311,35 @@ public function testFormatExceptions() { ); } + public function testFormatExceptionWithPreviousThrowable() { + $t = new TypeError("not a type error"); + $e = new Exception("an exception", 13, $t); + + $normalized = $this->normalizer->normalize([ + 'exception' => $e, + ]); + + self::assertEquals( + [ + 'exception' => [ + 'class' => get_class($e), + 'message' => $e->getMessage(), + 'code' => $e->getCode(), + 'file' => $e->getFile() . ':' . $e->getLine(), + 'trace' => $e->getTraceAsString(), + 'previous' => [ + 'class' => 'TypeError', + 'message' => 'not a type error', + 'code' => 0, + 'file' => $t->getFile() . ':' . $t->getLine(), + 'trace' => $t->getTraceAsString(), + ] + ] + ], $normalized + ); + self::assertTrue(isset($normalized['exception']['previous'])); + } + public function testUnknown() { $data = fopen('php://memory', 'rb'); fclose($data);