Skip to content

Commit

Permalink
Call the "report" method on Exceptions through the Container, injecti…
Browse files Browse the repository at this point in the history
…ng Dependencies

This is useful if you use a custom error reporting service but still want to keep
your Exceptions self-contained.

Backwards compatibility is ensured, as previously the report method was simply
called without any arguments, which is still possible if no type hints are added.
  • Loading branch information
spawnia committed Jan 25, 2019
1 parent 293b54c commit 2a7f8eb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Illuminate/Foundation/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ public function report(Exception $e)
return;
}

if (method_exists($e, 'report')) {
return $e->report();
$reportMethod = [$e, 'report'];
if (is_callable($reportMethod)) {
return $this->container->call($reportMethod);
}

try {
Expand Down
22 changes: 22 additions & 0 deletions tests/Foundation/FoundationExceptionsHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ public function testHandlerReportsExceptionAsContext()
$this->handler->report(new RuntimeException('Exception message'));
}

public function testHandlerCallsReportMethodWithDependencies()
{
$reporter = m::mock(ReportingService::class);
$this->container->instance(ReportingService::class, $reporter);
$reporter->shouldReceive('send')->withArgs(['Exception message']);

$this->handler->report(new ReportableException('Exception message'));
}

public function testReturnsJsonWithStackTraceWhenAjaxRequestAndDebugTrue()
{
$this->config->shouldReceive('get')->with('app.debug', null)->once()->andReturn(true);
Expand Down Expand Up @@ -139,3 +148,16 @@ public function toResponse($request)
return response()->json(['response' => 'My custom exception response']);
}
}

class ReportableException extends Exception
{
public function report(ReportingService $reportingService)
{
$reportingService->send($this->getMessage());
}
}

interface ReportingService
{
public function send($message);
}

0 comments on commit 2a7f8eb

Please sign in to comment.