Skip to content

Commit

Permalink
Merge pull request #90 from spatie/feature/use-custom-exception-context
Browse files Browse the repository at this point in the history
Use context from custom exceptions
  • Loading branch information
rubenvanassche authored May 5, 2022
2 parents 14e1219 + 151bcd9 commit 51e5daa
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/FlareMiddleware/AddExceptionInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ public function handle(Report $report, $next)
{
$throwable = $report->getThrowable();

$this->addUserDefinedContext($report);

if (! $throwable instanceof QueryException) {
return $next($report);
}
Expand All @@ -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);
}
}
}
30 changes: 30 additions & 0 deletions tests/FlareMiddleware/AddExceptionInformationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});

0 comments on commit 51e5daa

Please sign in to comment.