From 151bcd9eeef6eadef5e23c698e03ea3412dba862 Mon Sep 17 00:00:00 2001 From: Ruben Van Assche Date: Thu, 5 May 2022 17:35:13 +0200 Subject: [PATCH] Use context from custom exceptions --- .../AddExceptionInformation.php | 25 ++++++++++++++++ .../AddExceptionInformationTest.php | 30 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/FlareMiddleware/AddExceptionInformation.php b/src/FlareMiddleware/AddExceptionInformation.php index 82654e7b..0327f34d 100644 --- a/src/FlareMiddleware/AddExceptionInformation.php +++ b/src/FlareMiddleware/AddExceptionInformation.php @@ -12,6 +12,8 @@ public function handle(Report $report, $next) { $throwable = $report->getThrowable(); + $this->addUserDefinedContext($report); + if (! $throwable instanceof QueryException) { return $next($report); } @@ -22,4 +24,27 @@ public function handle(Report $report, $next) return $next($report); } + + private function addUserDefinedContext(Report $report): void + { + $throwable = $report->getThrowable(); + + if ($throwable === null) { + return; + } + + if (! method_exists($throwable, 'context')) { + return; + } + + $context = $throwable->context(); + + if (! is_array($context)) { + return; + } + + foreach ($context as $key => $value) { + $report->context($key, $value); + } + } } diff --git a/tests/FlareMiddleware/AddExceptionInformationTest.php b/tests/FlareMiddleware/AddExceptionInformationTest.php index 1aa1a494..575fb361 100644 --- a/tests/FlareMiddleware/AddExceptionInformationTest.php +++ b/tests/FlareMiddleware/AddExceptionInformationTest.php @@ -25,3 +25,33 @@ $this->assertArrayNotHasKey('exception', $context); }); + +it('will add user context when provided on a custom exception', function () { + $report = Flare::createReport(new class extends Exception { + public function context() + { + return [ + 'hello' => 'world', + ]; + } + }); + + $context = $report->toArray()['context']; + + expect($context['context']['hello'])->toBe('world'); +}); + +it('will only add arrays as user provided context', function () { + $report = Flare::createReport(new class extends Exception { + public function context() + { + return (object) [ + 'hello' => 'world', + ]; + } + }); + + $context = $report->toArray()['context']; + + expect($context)->not()->toHaveKey('context'); +});