From 2a7f8ebc35060ec2cb4c4f63d0d81e0e8bcc00b4 Mon Sep 17 00:00:00 2001 From: Benedikt Franke Date: Fri, 25 Jan 2019 09:42:45 +0100 Subject: [PATCH] Call the "report" method on Exceptions through the Container, injecting 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. --- .../Foundation/Exceptions/Handler.php | 5 +++-- .../FoundationExceptionsHandlerTest.php | 22 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Foundation/Exceptions/Handler.php b/src/Illuminate/Foundation/Exceptions/Handler.php index 6f6549da9234..1c45eddd2278 100644 --- a/src/Illuminate/Foundation/Exceptions/Handler.php +++ b/src/Illuminate/Foundation/Exceptions/Handler.php @@ -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 { diff --git a/tests/Foundation/FoundationExceptionsHandlerTest.php b/tests/Foundation/FoundationExceptionsHandlerTest.php index a27da4b4a81b..5ad2f57b7a37 100644 --- a/tests/Foundation/FoundationExceptionsHandlerTest.php +++ b/tests/Foundation/FoundationExceptionsHandlerTest.php @@ -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); @@ -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); +}